package com.ukefu.webim.web.handler.apps.sales;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.helper.JsonHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.IP;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.AiUtils;
import com.ukefu.util.asr.AsrResult;
import com.ukefu.util.client.NettyClients;
import com.ukefu.util.es.SearchTools;
import com.ukefu.util.es.UKDataBean;
import com.ukefu.util.freeswitch.model.CallCenterAgent;
import com.ukefu.util.mobile.MobileAddress;
import com.ukefu.util.mobile.MobileNumberUtils;
import com.ukefu.util.sms.CommandSms;
import com.ukefu.webim.service.acd.ServiceQuene;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.es.ContactsRepository;
import com.ukefu.webim.service.impl.CallOutQuene;
import com.ukefu.webim.service.repository.CallHangupRepository;
import com.ukefu.webim.service.repository.CallOutNamesRepository;
import com.ukefu.webim.service.repository.QueSurveyResultAnswerRepository;
import com.ukefu.webim.service.repository.QueSurveyResultPointRepository;
import com.ukefu.webim.service.repository.QueSurveyResultQuestionRepository;
import com.ukefu.webim.service.repository.QueSurveyResultRepository;
import com.ukefu.webim.service.repository.StatusEventRobotRepository;
import com.ukefu.webim.service.robot.RobotParam;
import com.ukefu.webim.service.robot.RobotReturnParam;
import com.ukefu.webim.util.MessageUtils;
import com.ukefu.webim.util.OnlineUserUtils;
import com.ukefu.webim.util.RobotTools;
import com.ukefu.webim.util.impl.AiMessageProcesserImpl;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.AgentUser;
import com.ukefu.webim.web.model.AiCallOutProcess;
import com.ukefu.webim.web.model.AiConfig;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.CallHangup;
import com.ukefu.webim.web.model.CallOutNames;
import com.ukefu.webim.web.model.Extention;
import com.ukefu.webim.web.model.Media;
import com.ukefu.webim.web.model.MetadataTable;
import com.ukefu.webim.web.model.QueSurveyAnswer;
import com.ukefu.webim.web.model.QueSurveyQuestion;
import com.ukefu.webim.web.model.QueSurveyResult;
import com.ukefu.webim.web.model.QueSurveyResultAnswer;
import com.ukefu.webim.web.model.QueSurveyResultPoint;
import com.ukefu.webim.web.model.QueSurveyResultQuestion;
import com.ukefu.webim.web.model.SalesMultianswer;
import com.ukefu.webim.web.model.SalesPatter;
import com.ukefu.webim.web.model.SalesPatterLevel;
import com.ukefu.webim.web.model.SalesPatterMedia;
import com.ukefu.webim.web.model.SalesPatterPoint;
import com.ukefu.webim.web.model.StatusEvent;
import com.ukefu.webim.web.model.StatusEventRobot;
import com.ukefu.webim.web.model.SysDic;
import com.ukefu.webim.web.model.SystemConfig;
import com.ukefu.webim.web.model.TableProperties;
import com.ukefu.webim.web.model.TransAgentProcess;
import com.ukefu.webim.web.model.UKeFuDic;
import com.ukefu.webim.web.model.VoiceResult;

import love.cq.util.StringUtil;

@Controller
@RequestMapping("/apps/robotsmartivr")
public class RobotSmartIVRController extends Handler {
	
	@Autowired
	private QueSurveyResultRepository queSurveyResultRes ;
	
	@Autowired
	private QueSurveyResultAnswerRepository queSurveyResultAnswerRes ;
	
	@Autowired
	private QueSurveyResultQuestionRepository questionResultRes ;
	
	@Autowired
	private QueSurveyResultPointRepository resultPointRes ;

	@Autowired
	private AiMessageProcesserImpl aiMessageProcesser;

	@Autowired
	private CallOutNamesRepository callOutNamesRes ;
	
	@Autowired
	private StatusEventRobotRepository statusEventRobotRes ;
	
	@Autowired
	private CallHangupRepository callHangupRes ;
	
	@Autowired
	private ContactsRepository contactsRes  ;

	private int waittime = 3000;

	
	@PersistenceContext
	private EntityManager entityManager;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Transactional
	@RequestMapping({"/asr"})
	@Menu(type = "callout", subtype = "smartivr", access = true)
	@ResponseBody
	public String asr(HttpServletRequest request, @Valid String content, @Valid String action) {
		SystemConfig systemConfig = UKTools.getSystemConfig();
		if(StringUtils.isNotBlank(content)){
			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n接收到来自ROBOT服务器的消息：[{}]",content);
			}
			RobotParam robotParam = UKTools.toObject(content, RobotParam.class);

			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n接收到RobotParam对象：[{}]",robotParam.toString());
			}

			if(StringUtils.isNotBlank(action)){
				robotParam.setAction(action);
				if(action.equalsIgnoreCase("reenter") && !StringUtils.isBlank(request.getParameter("text"))) {
					robotParam.setText(request.getParameter("text"));
				}
			}

			RobotReturnParam robotReturnParam = null;
			//机器人分机号 比如：9999
			String ext = robotParam.getUserid();

			//查出对应机器人分机号信息
			Extention extention = RobotTools.getExtention(ext);

			if (extention != null) {
				try {
					//话术 or 智能机器人
					if (!StringUtils.isBlank(extention.getAitype())
							&& extention.getAitype().equals(UKDataContext.AiType.BUSINESSAI.toString())) {
						robotReturnParam = salespatterasr(robotParam,extention);
					}else{
						robotReturnParam = aiasr(robotParam,extention);
					}
				}catch(Exception ex) {
					ex.printStackTrace();
				}
			} else {
				//找不到对应机器人
				List<String> voiceList = new ArrayList<>();
				voiceList.add("未配置机器人");
				robotReturnParam = fangyinList(voiceList, null);
			}
			
			String returnString = JsonHelper.toJson(robotReturnParam);
			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n返回给ROBOT服务器的消息：[{}]",returnString);
			}
			return returnString;
		}
		RobotReturnParam robotReturnParam = new RobotReturnParam();
		String returnString = JsonHelper.toJson(robotReturnParam);
		if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
			this.logger.info("\n返回给ROBOT服务器的消息：[{}]",returnString);
		}
		return returnString;
	}

	public RobotReturnParam salespatterasr(RobotParam robotParam,Extention extention) throws Exception {
		UKDataBean dataBean = null;

		//通话记录fs的通话的uuid
		String callid = robotParam.getCdrid().replace("-", "");
		//被叫
		String callerid = robotParam.getTelno();

		//名单ID
		String nameid = robotParam.getTaskid();

		//挂机时 taskid传回来 最后带了 -1？
		if(StringUtils.isNotBlank(robotParam.getParam1()) && "-99".equals(robotParam.getParam1()) && nameid.indexOf("-") > 0){
			nameid = nameid.substring(0,nameid.indexOf("-"));
		}
		RobotReturnParam robotReturnParam = null;
		StatusEvent statusEvent = RobotTools.getStatusEvent(robotParam.getCdrid(), extention.getOrgi()); 

		if(dataBean == null || dataBean.getValues() == null){
			if (statusEvent != null && StringUtils.isNotBlank(statusEvent.getDataid())) {
				PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), statusEvent.getDataid());
				if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
					dataBean = dataBeanList.getContent().get(0);
				}
			}
		}
		if(dataBean!=null && dataBean.getValues()!=null && dataBean.getValues().get("metaid")!=null) {
			dataBean.setTable(RobotTools.getMetadataTable(dataBean.getValues().get("metaid").toString()));
		}
		SystemConfig systemConfig = (SystemConfig) CacheHelper.getSystemCacheBean().getCacheObject("systemConfig", UKDataContext.SYSTEM_ORGI);
		if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
			this.logger.info("\n对应名单数据为：[{}]",dataBean == null?"null 空":UKTools.toJson(dataBean));
		}
		String action = robotParam.getAction();

		//通过action=enter 或aiuser 为空 判断是否第一次进入
		AiUser aiUserFirst = (AiUser) CacheHelper.getAiUserCacheBean().getCacheObject(callid,
				extention.getOrgi());
		AiCallOutProcess process = null;
		
		// 话术or问卷
		if (extention.getBustype().equals("sale")) {
			process = RobotTools.getAiProcess(extention.getProid(), extention.getOrgi());
		} else {
			process = RobotTools.getProcess(extention.getQueid(), extention.getOrgi()) ;
		}
		QueSurveyQuestion quest = null , nextQuestion = null ;
		AiUser aiUser = null ;
		//开始进入话术
		if ("enter".equals(action) || aiUserFirst == null) {
			aiUser = this.enterSmartIVR(callerid, callid, extention);
			ChatMessage retMessage = null;
			if (!StringUtils.isBlank(extention.getAitype())
					&& extention.getAitype().equals(UKDataContext.AiType.BUSINESSAI.toString())) {
				aiUser.setAitype(UKDataContext.AiType.BUSINESSAI.toString());
				if (!StringUtils.isBlank(extention.getBustype())
						&& (extention.getBustype().equals(UKDataContext.AiBussType.QUESURVEY.toString())
						|| extention.getBustype().equals(UKDataContext.AiBussType.SALE.toString()))) {
					boolean hangup = false;
					aiUser.setBusstype(extention.getBustype());
					if (process != null) {
						// 问卷结果主表
						QueSurveyResult queSurveyResult = new QueSurveyResult();
						queSurveyResult.setProcessid(process.getId());
						queSurveyResult.setEventid(robotParam.getCdrid());
						queSurveyResult.setCreater(aiUser.getUserid());
						queSurveyResult.setCreatetime(new Date());
						queSurveyResult.setOrgi(extention.getOrgi());
						queSurveyResult.setBusstype(extention.getBustype());
						if (statusEvent != null) {
							queSurveyResult.setDiscalled(statusEvent.getDiscalled());
							queSurveyResult.setDistype(statusEvent.getDistype());
						}
						if (dataBean != null) {
							if (dataBean.getValues() != null) {
								queSurveyResult.setActid((String)dataBean.getValues().get("actid"));
								queSurveyResult.setBatchid((String)dataBean.getValues().get("batid"));
								queSurveyResult.setFilterid((String)dataBean.getValues().get("filterid"));
								queSurveyResult.setFormfilterid((String)dataBean.getValues().get("calloutfilid"));
							}
							if (dataBean.getActivity() != null) {
								//queSurveyResult.setOrgan(dataBean.getActivity().getOrgan());
								queSurveyResult.setActid(dataBean.getActivity().getId());
							}
							if (dataBean.getBatch() != null) {
								queSurveyResult.setBatchid(dataBean.getBatch().getId());
							}
							queSurveyResult.setNameid(dataBean.getId());
						}
						// 问卷结果主表
						aiUser.setResult(queSurveyResult);
						aiUser.setQueresultid(queSurveyResult.getId());

						aiUser.setBussid(process.getId());
						
						// 欢迎语
						List<String> voices = new ArrayList<>();
						
						List<VoiceResult> vrList = new ArrayList<>();
						// 查询开始问题节点
						if (StringUtils.isNotBlank(process.getQuestionid())) {
							retMessage = newChatMsg(aiUser,null);

							// 开始节点欢迎语
							quest = RobotTools.getQuestion(extention.getOrgi(),
									process.getQuestionid()) ;
							if (quest != null) {
								/**
								 * 是否需要发送短信
								 */
								if(quest.isEnablesms() && !StringUtils.isBlank(quest.getSmsid())) {
									procesSMS(process, robotParam ,dataBean, statusEvent, aiUser, quest);
								}
								
								if (!StringUtils.isBlank(quest.getWvtype())
										&& quest.getWvtype().equals("voice")) {
									vrList.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
											null, quest.getQuevoice()));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setMessage(quest.getQuevoice());
									retMessage.setMessage(quest.getName());

								} else {
									vrList.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
											quest.getName(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									retMessage.setMessage(quest.getName());
								}
								aiUser.setDataid(quest.getId());
								aiUser.setAiqustitle(quest.getTitle());

								//设置是否允许打断 最大说话时长
								aiUser.setInterrupt(quest.isInterrupt());
								aiUser.setInterrupttime(quest.getInterrupttime() * 1000);
								aiUser.setMaxspreak(quest.getMaxspreak() * 1000);
								aiUser.setLanguage(process.getLanguage());
								//设置 等待超时时长
								aiUser.setLastreplytime(quest.getOvertime() * 1000 );
								aiUser.setDelaytime(process.getDelaytime() * 1000 );

								SysDic sysDic = (SysDic) UKeFuDic.getInstance().get(UKDataContext.UKEFU_SALES_LANG + "." + process.getLanguage() + ".subdiccode");
								if (sysDic != null && StringUtils.isNotBlank(sysDic.getDescription())) {
									aiUser.setLanguagepath(sysDic.getDescription());
								}

								//resultQuestion.setAnswer(StringUtils.isBlank(resultQuestion.getAnswer()) ? data.getMessage() : resultQuestion.getAnswer() + "," + data.getMessage());
								//resultQuestion.setAnswertimes(resultQuestion.getAnswertimes() + 1);

								// 话术 结束节点 结束通话hangup
								if (2 == quest.getQuetype()) {
									hangup = true;
									aiUser.setBussend(true);
								}
								//转接
								if (3 == quest.getQuetype()) {
									aiUser.setBridge(true);
									aiUser.setTrans(quest.getTrans());
								}
								//转接人工坐席 ， 判断是否有空闲坐席 ， 根据活动判断，要求活动名称不为空
								if (4 == quest.getQuetype()) {
									//
									String trans = transAgent(statusEvent , aiUser, quest.getId() ,quest, retMessage, vrList);
									if(!StringUtils.isBlank(trans)) {
										aiUser.setBridge(true);
										aiUser.setTrans(trans);
									}
								}
								//转话术节点
								if (5 == quest.getQuetype() && !StringUtils.isBlank(quest.getTransnode())) {
									//跳转 下一题
									nextQuestion = RobotTools.getQuestion(quest.getOrgi(),quest.getTransnode()) ;

									retMessage = nextQue(process ,robotParam, dataBean , statusEvent , aiUser,nextQuestion,vrList);
								}
								//记录问题结果
								//记录第一个节点
								if(process.isResult()) {
									QueSurveyResultQuestion resultQuestion = null;
									if (resultQuestion == null) {
										//new 一个
										resultQuestion = new QueSurveyResultQuestion();
										resultQuestion.setEventid(aiUser.getUsername());
										resultQuestion.setProcessid(aiUser.getBussid());
										resultQuestion.setQuestionid(aiUser.getDataid());
										resultQuestion.setOrgi(aiUser.getOrgi());
										resultQuestion.setCreatetime(new Date());
									}
									//统计当前问题数据
									resultQuestion.setScore(quest.getScore());
									if (aiUser.isBussend() || aiUser.isBridge()) {
										resultQuestion.setEndtime(new Date());
									}
									questionResultRes.save(resultQuestion);
									aiUser.getQuestionList().add(resultQuestion);
								}
							}
						}
						if (!StringUtils.isBlank(process.getWeltype())
								&& process.getWeltype().equals("voice")) {
							vrList.add(0, new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(), null,
									process.getWelvoice()));
							retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
							retMessage.setMessage(process.getWelword() + "," + retMessage.getMessage());
							retMessage.setExpmsg(process.getWelvoice() + "," + retMessage.getMessage());
						} else {
							vrList.add(0, new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
									process.getWelword(), null));
							retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
							retMessage.setMessage(process.getWelword() + "," + retMessage.getMessage());
							retMessage.setExpmsg(process.getWelword() + "," + retMessage.getMessage());
						}
						for (VoiceResult voiceResult : vrList) {
							if (UKDataContext.MediaTypeEnum.TEXT.toString()
									.equals(voiceResult.getVoicetype())) {
								String tts = null;
								if (!StringUtils.isBlank(voiceResult.getTts())) {
									tts = Jsoup.parse(voiceResult.getTts()).text();
									if (tts.length() > 300) {
										tts = tts.substring(0, 300);
									}
									voices.add(processMessage(tts, dataBean , aiUser));
								}
							} else {
								voices.add(processVoiceURL(voiceResult.getVoice(),extention.getOrgi()));
							}
						}
						if (voices.size() > 0) {
							MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
									retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
									UKDataContext.AiItemType.AIREPLY.toString(),
									UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());
							if (hangup) {
								// 第一个节点就结束通话
								robotReturnParam = hangUpList(voices, aiUser);
							} else if (aiUser.isBridge()) {
								robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
							} else {
								robotReturnParam = defaultplayback(voices, aiUser);
							}
						}
					}
				}
				/**
				 * 用于判断累计超时时长
				 */
				if(robotReturnParam!=null && 
						!StringUtils.isBlank(robotReturnParam.getAsrtimeout()) && 
						robotReturnParam.getAsrtimeout().matches("[\\d]{1,}")) {
					aiUser.setTimeout(Integer.parseInt(robotReturnParam.getAsrtimeout()));
				}
				CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser,
						UKDataContext.SYSTEM_ORGI);
			}
		} else {
			String param1 = robotParam.getParam1();
			aiUser = (AiUser) CacheHelper.getAiUserCacheBean().getCacheObject(callid,extention.getOrgi());
			//挂机
			if("-99".equals(param1)){
				// 电话挂断事件
				
				if (aiUser != null) {
//					ServiceQuene.processAiService(aiUser, extention.getOrgi(),
//							UKDataContext.EndByType.USER.toString());
//					AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean()
//							.getCacheObject(aiUser.getUserid(), UKDataContext.SYSTEM_ORGI);
//					if (agentUser != null) {
//						ServiceQuene.serviceFinish(agentUser, agentUser.getOrgi(),
//								UKDataContext.EndByType.USER.toString(), false);
//					}
					this.afterleave(aiUser, extention, dataBean,robotParam);
					
					if(statusEvent!=null && process.isEvent()) {
						callHangupRes.save(createHangupInfo(statusEvent, aiUser)) ;
					}
					/**
					 * 如果流程设置了 挂机保存数据 ， 则调用保存动作
					 */
					if(aiUser.isEvent() == false && process.isEvent() && aiUser.getNames().size() > 0) {
						OnlineUserUtils.processEvent(entityManager, aiUser, dataBean, aiUser.getOrgi(), statusEvent,false);
					}
					
					
					/**
					 * 保存联系人动作
					 */
					if(aiUser.getContacts() != null) {
						contactsRes.save(aiUser.getContacts()) ;
						
						if(aiUser.getContacts()!=null && dataBean != null && dataBean.getValues()!=null) {
							dataBean.getValues().put("conid",aiUser.getContacts().getId()) ;
							SearchTools.save(dataBean);
						}
					}
					
					//情况缓存数据
					CacheHelper.getAiUserCacheBean().delete(aiUser.getSessionid(), UKDataContext.SYSTEM_ORGI);
				}
			}else{
				String message = robotParam.getText();
				String param2 = robotParam.getParam2();
				/**
				 * 修正超时，如果空白识别内容的累计识别时长超过设置的时长，也判定为超时
				 */
				if(StringUtils.isBlank(message) && aiUser.getLastmsgtime() > 0 && 
						aiUser.getTimeout() > 0 && 
						(System.currentTimeMillis() - aiUser.getLastmsgtime())/1000 >= aiUser.getTimeout()) {
					message = "timeout" ;
					aiUser.setTimeoutnums(aiUser.getTimeoutnums() + (int)((System.currentTimeMillis() - aiUser.getLastmsgtime())/1000 / aiUser.getTimeout()));
				}
				// 进度流程，按需填写
				if ("timeout".equals(message)) {
					/**
					 * 重置超时计算时间
					 */
					aiUser.setLastmsgtime(0);
					//超时
					//记录当前问题节点信息
					boolean isaddNext = false;
					
					ChatMessage retMessage = null;
					if (aiUser != null) {
						List<VoiceResult> voiceResultList = new ArrayList<VoiceResult>();
						if (aiUser.isBussend()) {
							robotReturnParam = hangUp();
						} else {
							QueSurveyQuestion currentQues = RobotTools.getQuestion(aiUser.getOrgi(),
									aiUser.getDataid()) ;
							retMessage = newChatMsg(aiUser,null);

							String queSurveyResultAnswerStatus = null ;
							if (currentQues != null && !StringUtils.isBlank(currentQues.getOvertimerepeat())
									&& currentQues.getOvertimerepeat().matches("[0-9]")
									&& aiUser.getTimeoutnums() >= Integer
									.parseInt(currentQues.getOvertimerepeat())) {

								//超时 转接、挂断、 或 跳转其他节点
								if ("trans".equals(currentQues.getOvertimeoperate())) {
									aiUser.setBridge(true);
									aiUser.setTrans(currentQues.getOvertimetrans());
									queSurveyResultAnswerStatus = "trans";
								} else  if ("hangup".equals(currentQues.getOvertimeoperate())) {
									aiUser.setBussend(true);
									queSurveyResultAnswerStatus = "hangup";
									if (!StringUtils.isBlank(currentQues.getOvertimetypeup())
											&& currentQues.getOvertimetypeup().equals("voice")) {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
										retMessage.setMessage(StringUtils.isNotBlank(retMessage.getMessage()) ? retMessage.getMessage() + "," +currentQues.getOvertimewordup():currentQues.getOvertimewordup());
										retMessage.setExpmsg(StringUtils.isNotBlank(retMessage.getExpmsg()) ? retMessage.getExpmsg() + "," + currentQues.getOvertimevoiceup() : currentQues.getOvertimevoiceup());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
														null, currentQues.getOvertimevoiceup()));
									} else if (!StringUtils.isBlank(currentQues.getOvertimetypeup())
											&& currentQues.getOvertimetypeup().equals("text")){
										retMessage.setMessage(StringUtils.isNotBlank(retMessage.getMessage()) ? retMessage.getMessage() + "," +currentQues.getOvertimewordup():currentQues.getOvertimewordup());
										retMessage.setExpmsg(StringUtils.isNotBlank(retMessage.getExpmsg()) ? retMessage.getExpmsg() + "," +currentQues.getOvertimewordup():currentQues.getOvertimewordup());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
														currentQues.getOvertimewordup(), null));
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									}
								}else if(StringUtils.isNotBlank(currentQues.getOvertimeoperate())){
									//跳转 下一题
									nextQuestion = RobotTools.getQuestion(currentQues.getOrgi(),currentQues.getOvertimeoperate()) ;

									retMessage = nextQue(process ,robotParam,  dataBean , statusEvent , aiUser,nextQuestion,voiceResultList);
									isaddNext = true;
									queSurveyResultAnswerStatus = "next";
								}
							} else {
								if (currentQues != null) {
									if (!StringUtils.isBlank(currentQues.getOvertimetype())
											&& currentQues.getOvertimetype().equals("voice")) {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
										retMessage.setMessage(currentQues.getOvertimeword());
										retMessage.setExpmsg(currentQues.getOvertimevoice());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
														null, currentQues.getOvertimevoice()));
									} else {
										retMessage.setMessage(currentQues.getOvertimeword());
										retMessage.setExpmsg(currentQues.getOvertimeword());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
														currentQues.getOvertimeword(), null));
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									}

									aiUser.setTimeoutnums(aiUser.getTimeoutnums() + 1);
									CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser,
											UKDataContext.SYSTEM_ORGI);
								}
								queSurveyResultAnswerStatus = "overtime";
							}
							String qusresultid = null ; 
							if(process.isResult()) {
								boolean isadd = false;
								QueSurveyResultQuestion resultQuestion = aiUser.getQuestionList().size() > 0 ? aiUser.getQuestionList().getLast() : null;
								if (resultQuestion != null && !aiUser.getDataid().equals(resultQuestion.getQuestionid())) {
									isadd = true;
								}
								//问题不存在 或者 问题已经换了
								if (resultQuestion == null || (resultQuestion != null && !aiUser.getDataid().equals(resultQuestion.getQuestionid()))) {
									//new 一个
									resultQuestion = new QueSurveyResultQuestion();
									resultQuestion.setEventid(aiUser.getUsername());
									resultQuestion.setProcessid(aiUser.getBussid());
									resultQuestion.setQuestionid(aiUser.getDataid());
									resultQuestion.setOrgi(aiUser.getOrgi());
									resultQuestion.setCreatetime(new Date());
									isadd = true;
								}
								resultQuestion.setTimeouttimes(aiUser.getTimeoutnums() + 1);
								if ((aiUser.isBussend() || aiUser.isBridge()) && !isaddNext) {
									resultQuestion.setEndtime(new Date());
								}
								//记录问题结果
								if (isadd) {
									questionResultRes.save(resultQuestion);
									aiUser.getQuestionList().add(resultQuestion);
									qusresultid = resultQuestion.getId() ;
								}
							}
							/**
							 * 判断是否保存记录
							 */
							if(process.isResult() && isaddNext && nextQuestion != null){
								QueSurveyResultQuestion resultQuestion2 = null;
								//问题不存在 或者 问题已经换了
								if (resultQuestion2 == null) {
									//new 一个
									resultQuestion2 = new QueSurveyResultQuestion();
									resultQuestion2.setEventid(aiUser.getUsername());
									resultQuestion2.setProcessid(aiUser.getBussid());
									resultQuestion2.setQuestionid(aiUser.getDataid());
									resultQuestion2.setOrgi(aiUser.getOrgi());
									resultQuestion2.setCreatetime(new Date());
									resultQuestion2.setScore(nextQuestion.getScore());
								}
								//记录问题结果
								if (aiUser.isBussend() || aiUser.isBridge()) {
									resultQuestion2.setEndtime(new Date());
								}
								questionResultRes.save(resultQuestion2);
								aiUser.getQuestionList().add(resultQuestion2);
							}
							if(process.isResult()) {
								QueSurveyResultAnswer queSurveyResultAnswer = new QueSurveyResultAnswer();
								queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.OVERTIME.toString());
								queSurveyResultAnswer.setAnstatus(queSurveyResultAnswerStatus);
								//记录匹配的答案
								queSurveyResultAnswer.setResultquesid(qusresultid);
								queSurveyResultAnswer.setProcessid(currentQues.getProcessid());
								queSurveyResultAnswer.setQuestionid(currentQues.getId());
								queSurveyResultAnswer.setAnswerid(UKDataContext.AnswerType.OVERTIME.toString());
	
								queSurveyResultAnswer.setAnswermsg("");
								queSurveyResultAnswer.setAnswerexpmsg("");
	
								queSurveyResultAnswer.setAnswerscore(0);
								queSurveyResultAnswer.setCorrect("0");
								queSurveyResultAnswer.setResultid(aiUser.getQueresultid());
								queSurveyResultAnswer.setQuetype(currentQues.getQuetype());
								queSurveyResultAnswer.setOrgi(aiUser.getOrgi());
								queSurveyResultAnswer.setCreater(aiUser.getUserid());
								queSurveyResultAnswer.setCreatetime(new Date());
								queSurveyResultAnswer.setStatuseventid(robotParam.getCdrid());
								queSurveyResultAnswerRes.save(queSurveyResultAnswer);
							}
						}
						List<String> voices = new ArrayList<>();
						if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
							retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
							MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
									retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
									UKDataContext.AiItemType.AIREPLY.toString(),
									UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

							if (voiceResultList.size() > 0) {
								for (VoiceResult voiceResult : voiceResultList) {
									if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(voiceResult.getVoicetype())) {
										String tts = null;
										if (!StringUtils.isBlank(voiceResult.getTts())) {
											tts = Jsoup.parse(voiceResult.getTts()).text();
											if (tts.length() > 300) {
												tts = tts.substring(0, 300);
											}
											voices.add(processMessage(tts, dataBean, aiUser));
										}
									} else {
										voices.add(processVoiceURL(voiceResult.getVoice(),extention.getOrgi()));
									}
								}
							}
						}
						if (aiUser.isBussend()) {
							robotReturnParam = hangUpList(voices, aiUser);
						} else if (aiUser.isBridge()) {
							robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
						} else {
							robotReturnParam = defaultplayback(voices, aiUser);
						}
					}
					//没有设置超时语 继续asr
					if(robotReturnParam  == null){
						robotReturnParam = noop(true,aiUser);
					}
				}else{
					//TODO
					if(StringUtils.isBlank(param2)){
						//未播放完打断
						QueSurveyQuestion currentQues = RobotTools.getQuestion(aiUser.getOrgi(), aiUser.getDataid())  ;
						if (currentQues != null && currentQues.isInterrupt() && aiUser!=null && !StringUtils.isBlank(aiUser.getBussid()) && !StringUtils.isBlank(message)) {
							robotReturnParam = asrProcess(process , aiUser,robotParam, callid, extention, callerid, dataBean,true , statusEvent);
						}else{
							robotReturnParam = noop(false,aiUser);
						}
					}else{
						robotReturnParam = asrProcess(process, aiUser , robotParam, callid, extention, callerid, dataBean,false , statusEvent);
					}
				}
				/**
				 * 用于判断累计超时时长
				 */
				QueSurveyQuestion currentQues = RobotTools.getQuestion(aiUser.getOrgi(), aiUser.getDataid())  ;
				if(currentQues!=null && currentQues.getOvertime() > 0) {
					aiUser.setTimeout(currentQues.getOvertime());
				}else if(robotReturnParam!=null && 
						!StringUtils.isBlank(robotReturnParam.getAsrtimeout()) && 
						robotReturnParam.getAsrtimeout().matches("[\\d]{1,}")) {
					//未播放完打断
					aiUser.setTimeout(Integer.parseInt(robotReturnParam.getAsrtimeout()));
				}
				if(aiUser!=null) {
					CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
				}
			}
		}
		CallOutNames callOutNames = null ;
		if(statusEvent!=null && !StringUtils.isBlank(statusEvent.getNameid()) && !StringUtils.isBlank(statusEvent.getOrgi())) {
			callOutNames = (CallOutNames) CacheHelper.getCallOutCacheBean().getCacheObject(statusEvent.getNameid(), statusEvent.getOrgi());
			if(callOutNames == null) {
				callOutNames = callOutNamesRes.findByIdAndOrgi(statusEvent.getNameid(), statusEvent.getOrgi()) ;
			}
		}
		
		/**
		 * 保存 当前节点
		 */
		if(callOutNames!=null && aiUser != null && !StringUtils.isBlank(aiUser.getDataid())) {
			callOutNames.setAitransqus(aiUser.getDataid());
			callOutNames.setAitransans(aiUser.getAitransans());
			CacheHelper.getCallOutCacheBean().put(callOutNames.getDataid(), callOutNames, callOutNames.getOrgi());
		}
		if(robotReturnParam  == null){
			robotReturnParam = noop(false,null);
		}else {
			if(nextQuestion!=null && nextQuestion.isEnabledenoise()) {
				robotReturnParam.setHarmonic(String.valueOf(nextQuestion.getDenoise()));
			}else if(quest!=null && quest.isEnabledenoise()) {
				robotReturnParam.setHarmonic(String.valueOf(quest.getDenoise()));
			}
		}
		return robotReturnParam;
	}

	/**
	 * 智能机器人asr
	 * @param robotParam
	 * @param extention
	 * @return
	 * @throws Exception
	 */
	public RobotReturnParam aiasr(RobotParam robotParam,Extention extention) throws Exception {


			RobotReturnParam robotReturnParam = null;


			//通话记录fs的通话的uuid
			String callid = robotParam.getCdrid().replace("-", "");
			//被叫
			String callerid = robotParam.getTelno();
			//名单ID
			String nameid = robotParam.getTaskid();


			if (extention != null) {
				UKDataBean dataBean = null;

				StatusEvent statusEvent = RobotTools.getStatusEvent(robotParam.getCdrid(), extention.getOrgi());
				if(StringUtils.isNotBlank(nameid)){
					PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), nameid);
					if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
						dataBean = dataBeanList.getContent().get(0);
					}
				}else{
					if (statusEvent != null && StringUtils.isNotBlank(statusEvent.getDataid())) {
						PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), statusEvent.getDataid());
						if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
							dataBean = dataBeanList.getContent().get(0);
						}
					}
				}
				String action = robotParam.getAction();

				if ("enter".equals(action)) {
					AiUser aiUser = this.enterSmartIVR(callerid, callid, extention);
					ChatMessage retMessage = null;
						//智能机器人
					AiConfig aiConfig = AiUtils.initAiConfig(extention.getAiid(), extention.getOrgi());
					aiUser.setAitype(UKDataContext.AiType.SMARTAI.toString());
					aiUser.setLanguage(extention.getLanguage());
					aiUser.setLastreplytime(extention.getWaittime());
					SysDic sysDic = (SysDic) UKeFuDic.getInstance().get(UKDataContext.UKEFU_SALES_LANG + "." + extention.getLanguage() + ".subdiccode");
					if (sysDic != null && StringUtils.isNotBlank(sysDic.getDescription())) {
						aiUser.setLanguagepath(sysDic.getDescription());
					}
					if (aiConfig != null) {
						List<String> voices = new ArrayList<>();
						String me = processMessage(extention.getWelcomemsg(), dataBean, aiUser);
						voices.add(me);
						retMessage = newChatMsg(aiUser,null);

						retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
						retMessage.setMessage(me);
						retMessage.setExpmsg(me);
						MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
								retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
								UKDataContext.AiItemType.AIREPLY.toString(),
								UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

						robotReturnParam = defaultplayback(voices, aiUser);
					} else if (extention != null && !StringUtils.isBlank(extention.getErrormessage())) {
						List<String> voiceList = new ArrayList<>();
						voiceList.add(processMessage(extention.getErrormessage(), dataBean, aiUser));
						robotReturnParam = fangyinList(voiceList, null);
					} else {
						//fangyin("未配置机器人", aiUser);
						//找不到对应机器人
						List<String> voiceList = new ArrayList<>();
						voiceList.add("未配置机器人");
						robotReturnParam = fangyinList(voiceList, null);
					}
				}else {
					AiUser aiUser = (AiUser) CacheHelper.getAiUserCacheBean().getCacheObject(callid,
							extention.getOrgi());
					String param1 = robotParam.getParam1();
					//挂机
					if("-99".equals(param1)){
						// 电话挂断事件
						if (aiUser != null) {
							ServiceQuene.processAiService(aiUser, extention.getOrgi(),
									UKDataContext.EndByType.USER.toString());
							AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean()
									.getCacheObject(aiUser.getUserid(), UKDataContext.SYSTEM_ORGI);
							if (agentUser != null) {
								ServiceQuene.serviceFinish(agentUser, agentUser.getOrgi(),
										UKDataContext.EndByType.USER.toString(), false);
							}
							//智能机器人 返回hungup给外部机器人
							ChatMessage data = newChatMsg(aiUser,null);
							data.setAiid(extention.getAiid());
							data.setBustype(UKDataContext.MediaTypeEnum.HUNGUP.toString());
							data.setMessage(UKDataContext.MediaTypeEnum.HUNGUP.toString());
							aiMessageProcesser.chat(data);

							//情况缓存数据
							CacheHelper.getAiUserCacheBean().delete(aiUser.getSessionid(), UKDataContext.SYSTEM_ORGI);
						}
					}else{
						String message = robotParam.getText();
						// 进度流程，按需填写
						if ("timeout".equals(message)) {
							//超时
							ChatMessage retMessage = null;
							if (aiUser != null) {
								if (aiUser.isBussend()) {
									robotReturnParam = hangUp();
								} else {
										//智能机器人 返回hungup给外部机器人
										retMessage = newChatMsg(aiUser,null);
										retMessage.setAiid(extention.getAiid());

										//机器人重复提示音
										if (extention.getWaittiptimes() > 0 && aiUser.getRetimes() < extention.getWaittiptimes()) {
											if (!StringUtils.isBlank(extention.getWaitmsg())) {
												String[] msgList = extention.getWaitmsg().split("[;；]");
												if (msgList.length > aiUser.getRetimes()) {
													retMessage.setMessage(msgList[aiUser.getRetimes()]);
													retMessage.setExpmsg(msgList[aiUser.getRetimes()]);
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												} else {
													retMessage.setMessage(msgList[msgList.length - 1]);
													retMessage.setExpmsg(msgList[msgList.length - 1]);
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												}
											} else {
												retMessage.setMessage("您好，您还在吗？");
												retMessage.setExpmsg("您好，您还在吗？");
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
											}
											aiUser.setRetimes(aiUser.getRetimes() + 1);
											CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser,
													UKDataContext.SYSTEM_ORGI);
										} else {
											retMessage.setBustype(UKDataContext.MediaTypeEnum.HUNGUP.toString());
											retMessage.setMessage(!StringUtils.isBlank(extention.getErrormessage()) ? extention.getErrormessage() : "再见");
											retMessage.setExpmsg(!StringUtils.isBlank(extention.getErrormessage()) ? extention.getErrormessage() : "再见");
											retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
										}
//									}
								}

								if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
									retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
									MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
											retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
											UKDataContext.AiItemType.AIREPLY.toString(),
											UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());
									//智能机器人
									String retText = retMessage != null && !StringUtils.isBlank(retMessage.getMessage())
											? retMessage.getMessage()
											: extention.getTipmessage();
									if (!StringUtils.isBlank(retText)) {
										List<String> voices = new ArrayList<>();
										if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(retMessage.getMsgtype())) {
											String tts = null;
											if (!StringUtils.isBlank(retMessage.getMessage())) {
												tts = Jsoup.parse(retMessage.getMessage()).text();
												if (tts.length() > 300) {
													tts = tts.substring(0, 300);
												}
												voices.add(processMessage(tts,dataBean, aiUser));
											}
										} else {
											voices.add(retMessage.getMessage());
										}
										if (voices.size() > 0) {
											//外部机器人挂断
											if (UKDataContext.MediaTypeEnum.HUNGUP.toString().equalsIgnoreCase(retMessage.getBustype())) {
												robotReturnParam = hangUpList(voices, aiUser);
											} else if (UKDataContext.MediaTypeEnum.TRANS.toString().equalsIgnoreCase(retMessage.getBustype())) {
												//转接
												//map = beforeTransfer(retMessage.getCode(), voices, aiUser);
												robotReturnParam = transfer(retMessage.getCode(), voices, aiUser);
											} else {
												//map = fangyinList(voices, aiUser);
												robotReturnParam = defaultplayback(voices, aiUser);
											}
										}
									}
								}
								CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
							}
							//没有设置超时语 继续asr
							if(robotReturnParam  == null){
								robotReturnParam = noop(true,aiUser);
							}
						}else{
							if ("reenter".equals(action)) {
								aiUser = this.enterSmartIVR(callerid, callid, extention);
								CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
							}
							//智能机器人
							robotReturnParam = aiasrProcess(robotParam, callid, extention, callerid, dataBean , aiUser);
						}
					}

				}
			return robotReturnParam;
		}
		robotReturnParam = new RobotReturnParam();
		return robotReturnParam;
	}


	/**
	 *
	 * @param voice
	 * @return
	 */
	private String processVoiceURL(String voice,String orgi) {
		if (StringUtils.isBlank(voice)) {
			return null;
		}
		SystemConfig systemConfig = UKTools.getSystemConfig();
		String host = systemConfig.getIconstr();
		if (!StringUtils.isBlank(host)) {

			Media media = RobotTools.getMedia(voice,orgi);
			String filename = "";
			if(media != null){
				filename = media.getFilename();
			}
			if(StringUtils.isBlank(filename)){
				SalesPatterMedia sptMedia = RobotTools.getSalesMedia(voice,orgi);
				if (sptMedia != null) {
					filename = sptMedia.getFilename() ;
				}
			}
			if(StringUtils.isBlank(filename)){
				filename = "media/" + voice + ".mp3";
			}
			host = host + "/res/voice/" + filename;
            //url
			host = "U:" + host;
		}
		return host;
	}

	/**
	 * 组装文本
	 * @param message
	 * @param dataBean
	 * @return
	 */
	private String processMessage(String message, UKDataBean dataBean , AiUser aiUser) {
		/**
		 * 找名单数据，替换内容参数
		 */
		Object value = null;
		SystemConfig systemConfig = (SystemConfig) CacheHelper.getSystemCacheBean().getCacheObject("systemConfig", UKDataContext.SYSTEM_ORGI);
		if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
			this.logger.info("\n替换参数，对应名单数据为：[{}]",dataBean == null?"null 空":UKTools.toJson(dataBean));
		}
		if (dataBean != null && dataBean.getValues() != null) {
			MetadataTable table = RobotTools.getMetadataTable(dataBean.getType());
			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n替换参数，对应名单的数据结构为：[{}]",table == null?"null 空":UKTools.toJson(table));
			}
			if (table != null) {
				Map<String, Object> values = new HashMap<String, Object>();
				for (TableProperties tp : table.getTableproperty()) {
					values.put(tp.getName(), dataBean.getValues().get(tp.getFieldname()));
					values.put(tp.getFieldname(), dataBean.getValues().get(tp.getFieldname()));
				}
				Pattern pattern = Pattern.compile("\\[([\\S\\s]*?)\\]");
				Matcher matcher = pattern.matcher(message);
				StringBuffer strb = new StringBuffer();
				while (matcher.find()) {
					if (!StringUtils.isBlank(matcher.group(1)) && values.get(matcher.group(1)) != null) {
						matcher.appendReplacement(strb, values.get(matcher.group(1)).toString());
					} else {
						matcher.appendReplacement(strb, "");
					}
				}
				matcher.appendTail(strb);
				message = strb.toString();
				if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
					this.logger.info("\n替换参数后语句为：[{}]",message == null?"null 空":message);
				}
			}
		}
		if(aiUser!=null) {
			aiUser.setTtstimes(aiUser.getTtstimes()+1);
		}
		message = value != null ? value.toString() : message;
		//文字前要以 T：
		return "T:" + message;
	}

	/**
	 * 进入IVR
	 * @param callerid
	 * @param callid
	 * @param extention
	 * @return
	 * @throws Exception
	 */
	private AiUser enterSmartIVR(String callerid, String callid, Extention extention)
			throws Exception {
		MobileAddress address = MobileNumberUtils.getAddress(callerid);

		AiUser aiUser = new AiUser(callid, callid, System.currentTimeMillis(), extention.getOrgi(), new IP() , null);
		aiUser.setContextid(callid);
		if (address != null) {
			aiUser.getIpdata().setCountry(address.getCountry());
			aiUser.getIpdata().setProvince(address.getProvince());
			aiUser.getIpdata().setCity(address.getCity());
			aiUser.getIpdata().setIsp(address.getIsp());
			aiUser.getIpdata().setRegion(address.getProvince() + address.getCity() + address.getIsp());
		} else {
			aiUser.getIpdata().setRegion("内线");
		}
		aiUser.setCallnumber(extention.getExtention());
		aiUser.setSessionid(aiUser.getId());
		aiUser.setAppid(extention.getHostid());
		aiUser.setAiid(extention.getAiid());
		aiUser.setUsername(callerid);

		aiUser.setChannel(UKDataContext.ChannelTypeEnum.PHONE.toString());

//		AgentService agentService = ServiceQuene.processAiService(aiUser, extention.getOrgi(), null);
//		aiUser.setAgentserviceid(agentService.getId());
		aiUser.setAgentserviceid(callid);

		//放入缓存
		CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);

		aiUser.setEos_eng(extention.getEoseng());
		aiUser.setSos_eng(extention.getSoseng());
		aiUser.setEos_time(extention.getEostime());
		aiUser.setDenoise(extention.getDenoise());
		return aiUser;
	}

	/**
	 * 匹配不中结果 继续放音
	 * @param isNewAsr 是否新一段asr 还是继续播放旧的录音
	 * @return
	 */
	private RobotReturnParam noop(boolean isNewAsr,AiUser aiUser) {
		RobotReturnParam robotReturnParam = new RobotReturnParam(aiUser);
		if(isNewAsr){
			robotReturnParam.setAsrvoice("m00.wav");
		}
		robotReturnParam.setParam2("-9");
		return robotReturnParam;
	}

	/**
	 * 条件转接
	 * @param aiUser
	 * @param quest
	 * @param retMessage
	 * @param vrList
	 */
	private String transAgent(StatusEvent statusEvent , AiUser aiUser ,String id, TransAgentProcess quest , ChatMessage retMessage , List<VoiceResult> vrList) {
		/**
		 * 满足条件
		 */
		CallCenterAgent agent = null ;
		CallOutNames callOutNames = null ;
		if(statusEvent!=null && !StringUtils.isBlank(statusEvent.getNameid())) {
			callOutNames = (CallOutNames) CacheHelper.getCallOutCacheBean().getCacheObject(statusEvent.getNameid(), statusEvent.getOrgi());
			if(callOutNames == null) {
				callOutNames = callOutNamesRes.findByIdAndOrgi(statusEvent.getNameid(), statusEvent.getOrgi()) ;
			}
			if(callOutNames!=null) {
				int time = 0 ;
				if(aiUser.getTime() > 0) {
					time = (int) ((System.currentTimeMillis() - aiUser.getTime()) / 1000);
				}
				SysDic dic = null ;
				if(quest.isEnabletransfercon()) {
					if(!StringUtils.isBlank(quest.getTransferconditions()) && (dic = UKeFuDic.getInstance().getDicItem(quest.getTransferconditions()))!=null) {
						if (dic.getCode().equals("time") && (!StringUtils.isBlank(quest.getTransfervalue())
								&& quest.getTransfervalue().matches("[\\d]{1,3}")
								&& time >= Integer.parseInt(quest.getTransfervalue()))) {
							agent = CallOutQuene.updateAgentStatus(quest.getTransferactivity() , quest.getOrgi()) ;
						}else if (dic.getCode().equals("agents")) {
							agent = CallOutQuene.updateAgentStatus(quest.getTransferactivity() , quest.getOrgi()) ;
						}
					}
				}else {
					agent = CallOutQuene.updateAgentStatus(quest.getTransferactivity() , quest.getOrgi()) ;
				}
				if(agent!=null) {
					
					/**
					 * 保存状态
					 */
					callOutNames.setAi(true);
					callOutNames.setWaittime((int) (System.currentTimeMillis() - agent.getUpd()));
					callOutNames.setAieventid(statusEvent.getId());
					callOutNames.setAsrtimes(aiUser.getAsrtimes());
					callOutNames.setTtstimes(aiUser.getTtstimes());
					if(aiUser.getContacts()!=null) {
						callOutNames.setConid(aiUser.getContacts().getId());
					}
					
					callOutNames.setErrortimes(aiUser.getErrortimes());
					callOutNames.setTimeouttimes(aiUser.getTimeoutnums());
					callOutNames.setNmlinetimes(aiUser.getNmline());
					
					aiUser.setAgent(true);
					callOutNames.setAitrans(true);
					callOutNames.setAitransqus(id);
					callOutNames.setAitranstime(new Date());
					if(statusEvent.getAnswertime()!=null) {
						callOutNames.setAitransduration(time);
					}
					
					callOutNames.setOwnerforecast(quest.getTransferactivity());
					
					callOutNames.setAiext(agent.getExtno());
					callOutNames.setOwneruser(agent.getUserid());
					callOutNames.setMembersessionid(statusEvent.getId());
					callOutNamesRes.save(callOutNames) ;
				}else {
					callOutNames.setTransfaild(true);
					callOutNames.setAitrans(true);
				}
				if(quest instanceof SalesPatter) {
					callOutNames.setTranscon(true);
					if(dic!=null) {
						callOutNames.setTransconid(dic.getId());
					}
				}
				CacheHelper.getCallOutCacheBean().put(callOutNames.getDataid(), callOutNames, callOutNames.getOrgi());
			}
			if(agent!=null && callOutNames != null) {
				/**
				 * 
				 * 清空Voice，不再播放
				 */
				vrList.clear();
				
				if(!StringUtils.isBlank(quest.getTransferwvtype())) {
					if (quest.getTransferwvtype().equals("voice")) {
						vrList.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(), null,
								quest.getTransfervoice()));
						retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
						retMessage.setMessage(quest.getTransferword());
						retMessage.setExpmsg(quest.getTransferword());
					} else {
						vrList.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
								quest.getTransferword(), null));
						retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
						retMessage.setMessage(quest.getTransferword());
						retMessage.setExpmsg(quest.getTransferword());
					}
					/**
					 * 转人工坐席记录
					 */
					MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
							retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
							UKDataContext.AiItemType.AIREPLY.toString(),
							UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());
				}
				
				/**
				 * 转人工，发送Preview事件
				 */
				logger.info("推送人工坐席："+agent.getExtno() + " callOutNames:"+callOutNames.getAiext() + " id:"+callOutNames.getId() + " dataid:"+callOutNames.getDataid());
				NettyClients.getInstance().sendCallCenterMessage(callOutNames.getAiext(), "preview", callOutNames);
			}
		}
		return agent!=null ? agent.getExtno() : null ;
	}
	/**
	 * 话术 处理asr结果
	 * @param robotParam
	 * @param callid
	 * @param extention
	 * @param callerid
	 * @param dataBean
	 * @return
	 * @throws JSONException
	 */
	public RobotReturnParam asrProcess(AiCallOutProcess process,AiUser aiUser,RobotParam robotParam, String callid, Extention extention, String callerid,
										  UKDataBean dataBean,boolean isInterrupt , StatusEvent statusEvent) throws JSONException {
		RobotReturnParam robotReturnParam = null;
		if (aiUser != null && aiUser.isBussend() == false) {
			ChatMessage data = newChatMsg(aiUser,null);
			//TODO 返回 客户说话时长
			/*AsrResult asrResult = UKTools.parseAsrResult(robotParam.getCdrid(), robotParam.getText(),
					0);*/
			AsrResult asrResult = new AsrResult(robotParam.getCdrid(), robotParam.getText(),"0");

			aiUser.setAsrtimes(aiUser.getAsrtimes() + 1);
			
			if(StringUtils.isNotBlank(robotParam.getWavfile())){
				asrResult.setRecordpath(robotParam.getWavfile());
			}
			data.setAiid(extention.getAiid());
			if (asrResult != null && !StringUtils.isBlank(asrResult.getMessage())) {
				asrResult.setMessage(asrResult.getMessage().replaceAll("[\\p{P}+~$`^=|<>～｀＄＾＋＝｜＜＞￥×]", ""));
				if (asrResult.getMessage().endsWith("。")) {
					data.setMessage(asrResult.getMessage().substring(0, asrResult.getMessage().length() - 1));
				} else {
					data.setMessage(asrResult.getMessage());
				}
				data.setDuration((int) Math.ceil(asrResult.getSpeakms() / 1000f));
				data.setExpmsg(asrResult.getMessage());
				List<VoiceResult> voiceResultList = new ArrayList<VoiceResult>();

				//TODO 确认录音地址
				if (!StringUtil.isBlank(data.getMessage())) {
					if(!StringUtils.isBlank(asrResult.getRecordpath())) {
						if(asrResult.getRecordpath().indexOf("|") > 0) {
							data.setUrl(asrResult.getRecordpath().substring(0,asrResult.getRecordpath().indexOf("|")));
						}else {
							data.setUrl(asrResult.getRecordpath());
						}
					}
				}
				data.setMediaid(robotParam.getCdrid());
				if(!StringUtils.isBlank(data.getUrl()) && !StringUtils.isBlank(robotParam.getPlaytime()) && robotParam.getPlaytime().matches("[\\d]{1,}")) {
					data.setDuration(Integer.parseInt(robotParam.getPlaytime()));
					if(aiUser.getIgrvoicetime() < data.getDuration()) {
						aiUser.setIgrvoicetime(data.getDuration());
						aiUser.setIgrvoice(data.getUrl());
					}
				}
				/**
				 * 使用 ASR识别结果作为消息内容
				 */
				data.setMessage(data.getExpmsg());
				String qusresultid = null , queSurveyResultAnswerStatus = null; 
				/**
				 * 输入消息
				 */
				MessageUtils.createAiMessage(data, data.getAppid(), UKDataContext.ChannelTypeEnum.PHONE.toString(),
						UKDataContext.CallTypeEnum.IN.toString(), UKDataContext.AiItemType.USERINPUT.toString(),
						UKDataContext.MediaTypeEnum.TEXT.toString(), data.getUserid());
				
				ChatMessage retMessage = null;
					if (!StringUtils.isBlank(aiUser.getBusstype())
							&& (aiUser.getBusstype().equals(UKDataContext.AiBussType.QUESURVEY.toString())
							|| aiUser.getBusstype().equals(UKDataContext.AiBussType.SALE.toString()))
							&& !StringUtils.isBlank(aiUser.getDataid())) {
						//公共方法，从缓存中获取（提升性能）
						List<QueSurveyAnswer> ansList = RobotTools.loadAnswer(aiUser.getDataid(), extention.getOrgi()) ;
						QueSurveyQuestion currentQues = RobotTools.getQuestion(aiUser.getOrgi(),
								aiUser.getDataid()) ;
						//公共答案（公共方法，方便从缓存中获取）
						List<QueSurveyAnswer> publicAnsList = RobotTools.loadPubAnswer(currentQues.getProcessid(), extention.getOrgi(),false) ;
						List<QueSurveyAnswer> publicAnsInterruptList = RobotTools.loadPubAnswer(currentQues.getProcessid(), extention.getOrgi(),true) ;

						QueSurveyResult queSurveyResult = aiUser.getResult();
						//记录当前问题节点信息
						
						//匹配答案
						int ansnum = 0;// 问答次数
						boolean ismatch = false;

						boolean isrepeat = false;//重复
						QueSurveyAnswer ans = null;

						//优先匹配允许打断的公共词库
						if (!ismatch) {
							if (publicAnsInterruptList != null && publicAnsInterruptList.size() > 0) {
								for (QueSurveyAnswer ansobj : publicAnsInterruptList) {
									if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), false)) {
										ans = ansobj;
										ismatch = true;
										aiUser.setPubans(true);
										break;
									}
								}
							}

						}
						//优先匹配允许打断的公共词库
						if (!ismatch) {
							if (publicAnsInterruptList != null && publicAnsInterruptList.size() > 0) {
								for (QueSurveyAnswer ansobj : publicAnsInterruptList) {
									if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), true)) {
										ans = ansobj;
										ismatch = true;
										aiUser.setPubans(true);
										break;
									}
								}
							}

						}
						//非indexof查找一遍
						if (!ismatch) {
							for (QueSurveyAnswer ansobj : ansList) {
								ansnum = ansnum + 1;
								if (ansobj.isDefaultans() == false && matchKeyWord(ansobj.getAnswer(), data.getMessage(), false)) {
									ans = ansobj;
									ismatch = true;
									break;
								}
							}
						}
						//indexof查找一遍
						if (!ismatch) {
							for (QueSurveyAnswer ansobj : ansList) {
								ansnum = ansnum + 1;
								if (ansobj.isDefaultans() == false && matchKeyWord(ansobj.getAnswer(), data.getMessage(), true)) {
									ans = ansobj;
									ismatch = true;
									break;
								}
							}
						}
						//打断模式下 以下不匹配
						if(!isInterrupt){
							//设置的答案 不匹配就先寻找匹配重复语
							if (!ismatch) {
								if (!StringUtils.isBlank(currentQues.getReplykeyword())
										&& matchKeyWord(currentQues.getReplykeyword(), asrResult.getMessage(), false)) {
									ismatch = true;
									isrepeat = true;
								}
							}
							//设置的答案 不匹配就先寻找匹配重复语
							if (!ismatch) {
								if (!StringUtils.isBlank(currentQues.getReplykeyword())
										&& matchKeyWord(currentQues.getReplykeyword(), asrResult.getMessage(), true)) {
									ismatch = true;
									isrepeat = true;
								}
							}
							//不匹配再找公共词库
							if (!ismatch) {
								if (publicAnsList != null && publicAnsList.size() > 0) {
									for (QueSurveyAnswer ansobj : publicAnsList) {
										if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), false)) {
											ans = ansobj;
											ismatch = true;
											aiUser.setPubans(true);
											break;
										}
									}
								}

							}
							//不匹配再找公共词库
							if (!ismatch) {
								if (publicAnsList != null && publicAnsList.size() > 0) {
									for (QueSurveyAnswer ansobj : publicAnsList) {
										if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), true)) {
											ans = ansobj;
											ismatch = true;
											aiUser.setPubans(true);
											break;
										}
									}
								}

							}
						}

						if (!ismatch) {
							for (QueSurveyAnswer ansobj : ansList) {
								//未识别 目前答案为空
								if (StringUtils.isBlank(ansobj.getAnswer()) || ansobj.isDefaultans() == true) {
									ans = ansobj;
									break ;
								}
							}
						}
						//设置回答错误
						boolean isError = false;
						if(!isInterrupt){
							if(!StringUtils.isBlank(currentQues.getErrortype()) && !StringUtils.isBlank(currentQues.getErrorepeat()) &&
									!StringUtils.isBlank(currentQues.getErroroperate())){
								isError = true;
							}
						}
						if(ans!=null) {
							if(ans.isMultianswer()) {
								/**
								 * 启用了一问多答 , 查询答案库
								 */
								List<SalesMultianswer> salesMultianswerList = null ;
								if(ans.isMultianswer()) {
									int inx = 0 ;
									if(aiUser.getAns().get(ans.getId()) != null) {
										inx = aiUser.getAns().get(ans.getId()) ;
										salesMultianswerList = RobotTools.getMultianswer(extention.getOrgi(), ans.getId()) ;
										if(!StringUtils.isBlank(ans.getPolling()) && !ans.getPolling().equals("order")) {
											inx = new Random().nextInt(salesMultianswerList.size()+1) ;
										}
										if(inx > 0) {
											SalesMultianswer answer = salesMultianswerList.get(inx - 1) ;
											inx = inx + 1 ;
											if(inx > salesMultianswerList.size()) {
												inx = 0 ;
											}
											/**
											 * 替换ANS条件
											 */
											if(answer!=null) {
												ans.setHanguptype(answer.getType());
												if(!StringUtils.isBlank(answer.getWord())) {
													ans.setHangupmsg(answer.getWord());
												}
												if(!StringUtils.isBlank(answer.getVoice())) {
													ans.setHangupvoice(answer.getVoice());
												}
												if(!StringUtils.isBlank(answer.getBatjump())) {
													ans.setQueid(answer.getBatjump());
												}
												//支持打断
												if(answer.isBatinterrupt()) {
													ans.setInterrupt(answer.isBatinterrupt());
												}
											}
										}else {
											inx = inx + 1 ;
										}
										aiUser.getAns().put(ans.getId(), inx) ;
									}else{
										aiUser.getAns().put(ans.getId(), 1) ;
									}
								}
							}
						}
						if(queSurveyResult!=null) {
							qusresultid = queSurveyResult.getId() ;
						}

						QueSurveyQuestion nextQuestion = null;
						Boolean isAddNext = false;
								//下一题
						QueSurveyQuestion question = ans != null ? RobotTools.getQuestion(ans.getOrgi(),ans.getQueid()) : null;
						//下一题为结束（hangup） 或 下一题存在
						if (ans != null && !StringUtils.isBlank(ans.getQueid()) && ((ans.getQueid().equals("hangup")) || (ans.getQueid().equals("currentnode")) || ((!ans.getQueid().equals("hangup")) && (!ans.getQueid().equals("currentnode")) && question != null))) {
							aiUser.setAitransans(ans.getId());
							aiUser.setAianstitle(ans.getTitle());
							/**
							 * 处理业务数据
							 */
							if(ans.isBussop() && !StringUtils.isBlank(ans.getBusslist())) {
								SysDic dic = AiUtils.processAiUserNames(data.getMessage(), ans.getBusslist(), ans.isBussop(), aiUser,ans.getBussclist() , ans.getAnswer());
								if(dic!=null) {
									data.setBussop(true);
									data.setBusslist(dic.getCode());
								}
							}
							if (ans.getQueid().equals("hangup")) {// 结束
								if(question!=null) {
									aiUser.setDataid(question.getId());
									aiUser.setAiqustitle(question.getTitle());
								}
								retMessage = newChatMsg(aiUser,null);
								if (!StringUtils.isBlank(ans.getHanguptype())
										&& ans.getHanguptype().equals("voice")) {
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setExpmsg(ans.getHangupvoice());
									retMessage.setMessage(StringUtils.isNotBlank(ans.getHangupmsg())?ans.getHangupmsg():ans.getHangupvoice());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
													null, ans.getHangupvoice()));
								} else {
									retMessage.setMessage(ans.getHangupmsg());
									retMessage.setExpmsg(ans.getHangupmsg());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
													ans.getHangupmsg(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
								}
                                aiUser.setBussend(true);

                                queSurveyResultAnswerStatus = "end";// 结束

							} else if (ans.getQueid().equals("currentnode")) {//继续当前节点

								isAddNext = true;
								nextQuestion = question;

								aiUser.setDataid(currentQues.getId());
								aiUser.setAiqustitle(currentQues.getTitle());
								//设置是否允许打断 最大说话时长（公共答案支持打断）
								if(ans.isInterrupt()) {
									aiUser.setInterrupt(ans.isInterrupt());
								}else {
									aiUser.setInterrupt(currentQues.isInterrupt());
								}
								aiUser.setInterrupttime(currentQues.getInterrupttime() * 1000);
								aiUser.setMaxspreak(currentQues.getMaxspreak() * 1000);
								//设置 等待超时时长
								aiUser.setLastreplytime(currentQues.getOvertime() * 1000);
								aiUser.setBridge(false);

								retMessage = newChatMsg(aiUser,null);
								//播放当前匹配到的答案的 提示语
								if (!StringUtils.isBlank(ans.getHanguptype())
										&& ans.getHanguptype().equals("voice")) {
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setMessage(StringUtils.isNotBlank(ans.getHangupmsg())?ans.getHangupmsg():ans.getHangupvoice());
									retMessage.setExpmsg(ans.getHangupvoice());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
													null, ans.getHangupvoice()));
								} else if (StringUtils.isNotBlank(ans.getHangupmsg())) {
									retMessage.setMessage(ans.getHangupmsg());
									retMessage.setExpmsg(ans.getHangupmsg());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
													ans.getHangupmsg(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									retMessage.setMessage(ans.getHangupmsg());
								} else {
									if (!StringUtils.isBlank(currentQues.getWvtype())
											&& currentQues.getWvtype().equals("voice")) {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
										retMessage.setExpmsg(currentQues.getQuevoice());
										retMessage.setMessage(StringUtils.isNotBlank(currentQues.getName())?currentQues.getName():currentQues.getQuevoice());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
														null, currentQues.getQuevoice()));
									} else {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
										retMessage.setMessage(currentQues.getName());
										retMessage.setExpmsg(currentQues.getName());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
														currentQues.getName(), null));
									}
								}
								if (2 == currentQues.getQuetype()) {
									aiUser.setBussend(true);
									queSurveyResultAnswerStatus = "end";// 下个问题为结束
								} else if (3 == currentQues.getQuetype()) {
									aiUser.setBridge(true);
									aiUser.setTrans(currentQues.getTrans());
									queSurveyResultAnswerStatus = "trans";// 下个问题为转接
								} else if (4 == currentQues.getQuetype()) {
									//转接人工坐席 ， 判断是否有空闲坐席 ， 根据活动判断，要求活动名称不为空
									String trans = transAgent(statusEvent , aiUser, currentQues.getId() ,currentQues, retMessage, voiceResultList);
									if(!StringUtils.isBlank(trans)) {
										aiUser.setBridge(true);
										aiUser.setTrans(trans);
									}
								}else {
									queSurveyResultAnswerStatus = "next";// 下一题
								}

							} else {
								retMessage = nextQue(process ,robotParam, dataBean , statusEvent , aiUser,question,voiceResultList);
								isAddNext = true;
								nextQuestion = question;
								//下个问题
                                if (2 == question.getQuetype()) {
									//resultQuestion.setScore(resultQuestion.getScore() + question.getScore());
                                    // 一个问题为结束节点 结束通话hangup
                                	queSurveyResultAnswerStatus = "end";// 下个问题为结束
                                } else if (3 == question.getQuetype()) {
                                	queSurveyResultAnswerStatus = "trans";// 下个问题为转接
                                } else if (4 == question.getQuetype()) {
                                	queSurveyResultAnswerStatus = "transagent";// 下个问题为转接
                                } else {
                                	queSurveyResultAnswerStatus = "next";// 下一题
                                }
							}
							if (!StringUtils.isBlank(currentQues.getConfirmtype())
									&& currentQues.getConfirmtype().equals("voice")) {
								retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
								retMessage.setExpmsg(retMessage.getExpmsg() + "," + currentQues.getConfirmvoice());
								String text = currentQues.getConfirmword().replaceAll("\\{text\\}",
										asrResult.getMessage());
								retMessage.setMessage(retMessage.getMessage() + "," + (StringUtils.isNotBlank(text) ? (text + ",") : "") + currentQues.getConfirmvoice());
								voiceResultList.add(0,
										new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(), null,
												currentQues.getConfirmvoice()));
							} else {
								String text = currentQues.getConfirmword().replaceAll("\\{text\\}",
										asrResult.getMessage());
								retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
								retMessage.setMessage(retMessage.getMessage() + "," + (StringUtils.isNotBlank(text) ? (text + ",") : "") + text);
								retMessage.setExpmsg(retMessage.getExpmsg() + "," + (StringUtils.isNotBlank(text) ? (text + ",") : "") + text);
								voiceResultList.add(0, new VoiceResult(
										UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
							}
						}

						// 重复 或 错误语
						if (retMessage == null && !isInterrupt) {
							if (currentQues != null) {

								if (!StringUtils.isBlank(currentQues.getReplykeyword())
										&& matchKeyWord(currentQues.getReplykeyword(), asrResult.getMessage(), true)) {
									retMessage = newChatMsg(aiUser,null);


									if (!StringUtils.isBlank(currentQues.getReplyrepeat())
											&& currentQues.getReplyrepeat().matches("[0-9]")
											&& aiUser.getRetimes() >= Integer.parseInt(currentQues.getReplyrepeat())) {
										if ("trans".equals(currentQues.getReplyoperate())) {
											aiUser.setBridge(true);
											aiUser.setTrans(currentQues.getReplytrans());
											queSurveyResultAnswerStatus = "trans";
										} else if("hangup".equals(currentQues.getReplyoperate())) {
											aiUser.setBussend(true);
											queSurveyResultAnswerStatus = "end";
											if (!StringUtils.isBlank(currentQues.getReplytypeup())
													&& currentQues.getReplytypeup().equals("voice")) {
												if (!StringUtils.isBlank(currentQues.getReplyvoiceup())) {
													voiceResultList.add(
															new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																	null, currentQues.getReplyvoiceup()));
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());

													String text = currentQues.getReplywordup().replaceAll("\\{text\\}",
															asrResult.getMessage());

													retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text)?text:currentQues.getReplyvoiceup()));
													retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getReplyvoiceup());
												}
											} else {
												String text = currentQues.getReplywordup().replaceAll("\\{text\\}",
														asrResult.getMessage());
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text);
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text);

											}
										}else if(StringUtils.isNotBlank(currentQues.getReplyoperate())){
											//跳转 下一题
											nextQuestion = RobotTools.getQuestion(currentQues.getOrgi(),currentQues.getReplyoperate()) ;

											isAddNext = true;
											retMessage = nextQue(process ,robotParam,  dataBean , statusEvent , aiUser,nextQuestion,voiceResultList);
											queSurveyResultAnswerStatus = "next";
										}

									} else {
										//未达到次数时 才播放重复提示语
										if (!StringUtils.isBlank(currentQues.getReplytype())
												&& currentQues.getReplytype().equals("voice")) {
											if (!StringUtils.isBlank(currentQues.getReplyvoice())) {
												voiceResultList.add(
														new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																null, currentQues.getReplyvoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());

												String text = currentQues.getReplyword().replaceAll("\\{text\\}",
														asrResult.getMessage());

												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text)?text:currentQues.getReplyvoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getReplyvoice());

											}
										} else {
											String text = currentQues.getReplyword().replaceAll("\\{text\\}",
													asrResult.getMessage());
											voiceResultList.add(new VoiceResult(
													UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
											retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

											retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text);
											retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text);

										}

										// retMessage.setMessage(currentQues.getReplyword() + "," +
										// currentQues.getName());
										aiUser.setRetimes(aiUser.getRetimes() + 1);
										queSurveyResultAnswerStatus = "repeat";
									}
								} else {
									//问卷 回答错误语
									if(isError) {
										retMessage = newChatMsg(aiUser, null);
										String text = currentQues.getErrorword().replaceAll("\\{text\\}",
												asrResult.getMessage());

										if (!StringUtils.isBlank(currentQues.getErrorepeat())
												&& currentQues.getErrorepeat().matches("[1-9]") && 
												aiUser.getErrortimes() >= Integer.parseInt(currentQues.getErrorepeat())) {
											isAddNext = processError(process , robotParam,dataBean ,aiUser, currentQues, voiceResultList, asrResult.getMessage(), retMessage, nextQuestion, statusEvent) ;
										} else {
											//未达到次数时 才播放错误提示语
											if (!StringUtils.isBlank(currentQues.getErrortype())
													&& currentQues.getErrortype().equals("voice")) {
												if (!StringUtils.isBlank(currentQues.getErrorvoice())) {
													voiceResultList.add(
															new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																	null, currentQues.getErrorvoice()));
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());

													retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text) ? text : currentQues.getErrorvoice()));
													retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getErrorvoice());

												}
											} else {

												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text);
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text);
											}
											// retMessage.setMessage(currentQues.getErrorword());
											aiUser.setErrortimes(aiUser.getErrortimes() + 1);
											queSurveyResultAnswerStatus = "error";
										}
									}
								}
							}
						}

						if (retMessage == null && !isrepeat && !isError && !isInterrupt) {//非重复节点 且没有设置回答错误 非打断
							//问卷则自动寻找下一题or话术结束
							if (UKDataContext.AiBussType.SALE.toString().equals(aiUser.getBusstype())) {
								//话术结束
								// 播放结束语音
								if(process == null) {
									process = RobotTools.getAiProcess(extention.getProid(), extention.getOrgi());
								}
								retMessage = newChatMsg(aiUser,null);

								//话术结束语
								if (!StringUtils.isBlank(process.getEndtype())
										&& process.getEndtype().equals("voice")) {
									voiceResultList.add(
											new VoiceResult(
													UKDataContext.MediaTypeEnum.VOICE.toString(), null,
													process.getEndvoice()));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setExpmsg(process.getEndvoice());
									retMessage.setMessage(StringUtils.isNotBlank(process.getEndword())?process.getEndword():process.getEndvoice());
								} else {
									voiceResultList.add(
											new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
													process.getEndword(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									retMessage.setMessage(process.getEndword());
									retMessage.setExpmsg(
											process.getEndword());
								}

								aiUser.setBussend(true);

								queSurveyResultAnswerStatus = "end";// 结束

							} else {
								//问卷则自动寻找下一题
								/**
								 * 如果是最后一条，直接播放结束语音，否则进入到 下一条
								 */
								List<QueSurveyQuestion> quesList = RobotTools.loadQuestion(aiUser.getOrgi(), aiUser.getBussid());

								for (QueSurveyQuestion ques : quesList) {
									if (ques.getId().equals(aiUser.getDataid())) {
										if ((quesList.indexOf(ques) + 1) >= quesList.size()) {
											// 播放结束语音
											if(process == null) {
												process = RobotTools.getProcess(aiUser.getBussid(), aiUser.getOrgi()) ;
											}
											retMessage = newChatMsg(aiUser,null);

											if (!StringUtils.isBlank(ques.getConfirmtype())
													&& ques.getConfirmtype().equals("voice")) {
												voiceResultList.add(0,
														new VoiceResult(
																UKDataContext.MediaTypeEnum.VOICE.toString(), null,
																ques.getConfirmvoice()));
												retMessage.setExpmsg(ques.getConfirmvoice());
												String text = ques.getConfirmword().replaceAll("\\{text\\}",
														asrResult.getMessage());
												retMessage.setMessage(StringUtils.isNotBlank(text)?text:ques.getConfirmvoice());
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
											} else {
												String text = ques.getConfirmword().replaceAll("\\{text\\}",
														asrResult.getMessage());
												voiceResultList.add(0, new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMessage(text);
												retMessage.setExpmsg(text);
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
											}

											if (!StringUtils.isBlank(process.getEndtype())
													&& process.getEndtype().equals("voice")) {
												voiceResultList.add(
														new VoiceResult(
																UKDataContext.MediaTypeEnum.VOICE.toString(), null,
																process.getEndvoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(process.getEndword())?process.getEndword():process.getEndvoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + process.getEndvoice());
											} else {
												voiceResultList.add(
														new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
																process.getEndword(), null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + process.getEndword());
												retMessage.setExpmsg(retMessage.getMessage());
											}

											aiUser.setBussend(true);

											queSurveyResultAnswerStatus = "end";// 结束

										} else {
											QueSurveyQuestion nextquestion = quesList.get(quesList.indexOf(ques) + 1);
											isAddNext = true;
											nextQuestion = nextquestion;
											aiUser.setDataid(nextquestion.getId());
											aiUser.setAiqustitle(nextquestion.getTitle());
											//设置是否允许打断 最大说话时长
											aiUser.setInterrupt(nextquestion.isInterrupt());
											aiUser.setInterrupttime(nextquestion.getInterrupttime() * 1000);
											aiUser.setMaxspreak(nextquestion.getMaxspreak() * 1000);
											//设置 等待超时时长
											aiUser.setLastreplytime(nextquestion.getOvertime() * 1000);
											retMessage = newChatMsg(aiUser,null);

											if (!StringUtils.isBlank(ques.getConfirmtype())
													&& ques.getConfirmtype().equals("voice")) {
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.VOICE.toString(), null,
														ques.getConfirmvoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(ques.getConfirmword())?ques.getConfirmword():ques.getConfirmvoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + ques.getConfirmvoice());
											} else {
												String text = ques.getConfirmword().replaceAll("\\{text\\}",
														asrResult.getMessage());
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + ques.getConfirmword());
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + ques.getConfirmword());
											}
											//下一个问题欢迎语
											if (!StringUtils.isBlank(nextquestion.getWvtype())
													&& nextquestion.getWvtype().equals("voice")) {
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.VOICE.toString(), null,
														nextquestion.getQuevoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(nextquestion.getName())?nextquestion.getName():nextquestion.getQuevoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + nextquestion.getQuevoice());
											} else {
												voiceResultList.add(
														new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
																nextquestion.getName(), null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + nextquestion.getName());
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + nextquestion.getName());
											}
											queSurveyResultAnswerStatus = "next";// 下一题
											if (2 == nextquestion.getQuetype()) {
												// 一个问题为结束节点 结束通话hangup
												aiUser.setBussend(true);
												queSurveyResultAnswerStatus = "end";
											} else if (3 == nextquestion.getQuetype()) {
												aiUser.setBridge(true);
												aiUser.setTrans(nextquestion.getTrans());
												queSurveyResultAnswerStatus = "trans";// 下个问题为转接
											} else if (4 == nextquestion.getQuetype()) {
												aiUser.setBridge(true);
												aiUser.setTrans(nextquestion.getTrans());
												queSurveyResultAnswerStatus = "trans";// 下个问题为转接
											}

										}
										break;
									}
								}
							}
						}
						if(process.isResult()) {
							QueSurveyResultAnswer queSurveyResultAnswer = new QueSurveyResultAnswer();
							if(ans != null){
								queSurveyResultAnswer.setAnswer(ans != null ? ans.getAnswer() : data.getMessage());
								if("0".equals(ans.getAnstype())){
									if(ans.isInterrupt()){
										queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER_INTERRUPT.toString());
									}else{
										queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER.toString());
									}
								}else if("1".equals(ans.getAnstype())){
									if(ans.isInterrupt()){
										queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER_PUBLIC_INTERRUPT.toString());
									}else{
										queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER_PUBLIC.toString());
									}
								}
							}
							queSurveyResultAnswer.setAnstatus(queSurveyResultAnswerStatus);
							queSurveyResultAnswer.setResultid(qusresultid);
							boolean isadd = false;
							QueSurveyResultQuestion resultQuestion = aiUser.getQuestionList().size() > 0 ? aiUser.getQuestionList().getLast() : null;
							if (resultQuestion != null && !resultQuestion.getQuestionid().equals(currentQues.getId())) {
								resultQuestion.setEndtime(new Date());
								isadd = true;
							}
							//问题不存在 或者 问题已经换了
							if (resultQuestion == null || (resultQuestion != null && !resultQuestion.getQuestionid().equals(currentQues.getId()))) {
								//new 一个
								resultQuestion = new QueSurveyResultQuestion();
								resultQuestion.setEventid(aiUser.getUsername());
								resultQuestion.setProcessid(aiUser.getBussid());
								resultQuestion.setQuestionid(aiUser.getDataid());
								resultQuestion.setOrgi(aiUser.getOrgi());
								resultQuestion.setCreatetime(new Date());
								isadd = true;
	
							}
							//统计当前问题数据
							resultQuestion.setScore(currentQues.getScore());
							resultQuestion.setAnswer(StringUtils.isBlank(resultQuestion.getAnswer()) ? data.getMessage() : resultQuestion.getAnswer() + "," + data.getMessage());
							resultQuestion.setAnswertimes(resultQuestion.getAnswertimes() + 1);
							if (aiUser.isBussend()|| aiUser.isBridge()) {
								resultQuestion.setEndtime(new Date());
							}
							//记录问题结果
							if (isadd) {
								questionResultRes.save(resultQuestion);
								aiUser.getQuestionList().add(resultQuestion);
								qusresultid = resultQuestion.getId() ;
							}
						
							if(isAddNext && nextQuestion != null){
								QueSurveyResultQuestion resultQuestion2 = null;
								//问题不存在 或者 问题已经换了
								if (resultQuestion2 == null) {
									//new 一个
									resultQuestion2 = new QueSurveyResultQuestion();
									resultQuestion2.setEventid(aiUser.getUsername());
									resultQuestion2.setProcessid(aiUser.getBussid());
									resultQuestion2.setQuestionid(aiUser.getDataid());
									resultQuestion2.setOrgi(aiUser.getOrgi());
									resultQuestion2.setCreatetime(new Date());
									resultQuestion2.setScore(nextQuestion.getScore());
								}
								//记录问题结果
								if (aiUser.isBussend() || aiUser.isBridge()) {
									resultQuestion2.setEndtime(new Date());
								}
								questionResultRes.save(resultQuestion2);
								aiUser.getQuestionList().add(resultQuestion2);
							}
						

							//记录匹配的答案
							queSurveyResultAnswer.setResultquesid(qusresultid);
							queSurveyResultAnswer.setProcessid(currentQues.getProcessid());
							queSurveyResultAnswer.setQuestionid(currentQues.getId());
							queSurveyResultAnswer.setAnswerid(ans != null ? ans.getId() : null);
	
							queSurveyResultAnswer.setAnswermsg(data.getMessage());
							queSurveyResultAnswer.setAnswerexpmsg(data.getExpmsg());
	
							queSurveyResultAnswer.setAnswerscore(ans != null ? ans.getAnswerscore() : 0);
							queSurveyResultAnswer.setCorrect(ans != null ? ans.getCorrect() : "0");
	
							queSurveyResultAnswer.setQuetype(currentQues.getQuetype());
							queSurveyResultAnswer.setOrgi(aiUser.getOrgi());
							queSurveyResultAnswer.setCreater(aiUser.getUserid());
							queSurveyResultAnswer.setCreatetime(new Date());
	
							if(StringUtils.isBlank(queSurveyResultAnswer.getAnswertype())){
								queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.UNMATCH.toString());
							}
							queSurveyResultAnswer.setStatuseventid(robotParam.getCdrid());
							queSurveyResultAnswerRes.save(queSurveyResultAnswer);
							/*}*/
							if(queSurveyResult!=null) {
								queSurveyResult.setAnswertimes(ansnum);// 回答次数
							}
						}
					}
				List<String> voices = new ArrayList<>();
				/**
				 * 回复消息
				 */
				if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
					retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
							retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
							UKDataContext.AiItemType.AIREPLY.toString(),
							UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

					if (voiceResultList.size() > 0) {
						for (VoiceResult voiceResult : voiceResultList) {
							if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(voiceResult.getVoicetype())) {
								String tts = null;
								if (!StringUtils.isBlank(voiceResult.getTts())) {
									tts = Jsoup.parse(voiceResult.getTts()).text();
									if (tts.length() > 300) {
										tts = tts.substring(0, 300);
									}
									voices.add(processMessage(tts, dataBean, aiUser));
								}
							} else {
								voices.add(processVoiceURL(voiceResult.getVoice(),extention.getOrgi()));
							}
						}
					}
				}
				CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
				
				if (aiUser.isBussend()) {
					robotReturnParam = hangUpList(voices, aiUser);
				} else if (aiUser.isBridge()) {
					robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
				} else {
					robotReturnParam = defaultplayback(voices, aiUser);
				}
				aiUser.setLastmsgtime(0);
			}else {
				/**
				 * 累计 空白内容时长
				 */
				if(aiUser.getLastmsgtime() == 0) {
					aiUser.setLastmsgtime(System.currentTimeMillis());
				}
			}
		} else {
			//robotReturnParam = hangUp();
		}
		if (robotReturnParam == null) {
			robotReturnParam = noop(true,aiUser);
		}
		return robotReturnParam;
	}
	/**
	 * 
	 * @param aiUser
	 * @param currentQues
	 * @param queSurveyResultAnswer
	 * @param voiceResultList
	 * @param asrResult
	 * @param retMessage
	 * @param nextQuestion
	 * @param statusEvent
	 * @return
	 */
	private boolean processError(AiCallOutProcess process,RobotParam robotParam ,UKDataBean dataBean ,AiUser aiUser, QueSurveyQuestion currentQues,List<VoiceResult> voiceResultList, String asrResultMessage,
			ChatMessage retMessage, QueSurveyQuestion nextQuestion, StatusEvent statusEvent) {
		boolean isAddNext = false;
		if ("trans".equals(currentQues.getErroroperate())) {
			aiUser.setBridge(true);
			aiUser.setTrans(currentQues.getErrortrans());
		} else if ("hangup".equals(currentQues.getErroroperate())) {
			aiUser.setBussend(true);
			if (!StringUtils.isBlank(currentQues.getErrortypeup())
					&& currentQues.getErrortypeup().equals("voice")) {
				if (!StringUtils.isBlank(currentQues.getErrorvoiceup())) {
					voiceResultList.add(
							new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
									null, currentQues.getErrorvoiceup()));

					String text1 = currentQues.getErrorwordup().replaceAll("\\{text\\}",
							asrResultMessage);

					retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text1) ? text1 : currentQues.getErrorvoiceup()));
					retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getErrorvoiceup());

					retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
				}
			} else if(!StringUtils.isBlank(currentQues.getErrortypeup())
					&& currentQues.getErrortypeup().equals("text")){
				String text1 = currentQues.getErrorwordup().replaceAll("\\{text\\}",
						asrResultMessage);
				voiceResultList.add(new VoiceResult(
						UKDataContext.MediaTypeEnum.TEXT.toString(), text1, null));
				retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

				retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text1);
				retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text1);

			}
		} else if (StringUtils.isNotBlank(currentQues.getErroroperate())) {
			//跳转 下一题
			nextQuestion = RobotTools.getQuestion(currentQues.getOrgi(), currentQues.getErroroperate()) ;

			if(nextQuestion!=null) {
				isAddNext = true;
				
				retMessage = nextQue(process , robotParam, dataBean , statusEvent , aiUser, nextQuestion, voiceResultList);
			}
		}
		return isAddNext ;
	}
	
	
	/**
	 * 
	 * @param aiUser
	 * @param currentQues
	 * @param queSurveyResultAnswer
	 * @param voiceResultList
	 * @param asrResult
	 * @param retMessage
	 * @param nextQuestion
	 * @param statusEvent
	 * @return
	 */
	private boolean processNmline(AiCallOutProcess process ,RobotParam robotParam, UKDataBean dataBean ,AiUser aiUser, QueSurveyQuestion currentQues,
			QueSurveyResultAnswer queSurveyResultAnswer, List<VoiceResult> voiceResultList, String asrResultMessage,
			ChatMessage retMessage, QueSurveyQuestion nextQuestion, StatusEvent statusEvent) {
		boolean isAddNext = false;
		if ("trans".equals(currentQues.getNmlineoperate())) {
			aiUser.setBridge(true);
			aiUser.setTrans(currentQues.getNmlinetrans());
			if(queSurveyResultAnswer!=null) {
				queSurveyResultAnswer.setAnstatus("trans");
			}
		} else if ("hangup".equals(currentQues.getNmlineoperate())) {
			aiUser.setBussend(true);
			if(queSurveyResultAnswer!=null) {
				queSurveyResultAnswer.setAnstatus("end");
			}
			if (!StringUtils.isBlank(currentQues.getNmlinetypeup())
					&& currentQues.getNmlinetypeup().equals("voice")) {
				if (!StringUtils.isBlank(currentQues.getNmlinevoiceup())) {
					voiceResultList.add(
							new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
									null, currentQues.getNmlinevoiceup()));

					String text1 = currentQues.getNmlinewordup().replaceAll("\\{text\\}",
							asrResultMessage);

					retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text1) ? text1 : currentQues.getNmlinevoiceup()));
					retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getNmlinevoiceup());

					retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
				}
			} else if(!StringUtils.isBlank(currentQues.getNmlinetypeup())
					&& currentQues.getNmlinetypeup().equals("text")){
				String text1 = currentQues.getNmlinewordup().replaceAll("\\{text\\}",
						asrResultMessage);
				voiceResultList.add(new VoiceResult(
						UKDataContext.MediaTypeEnum.TEXT.toString(), text1, null));
				retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

				retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text1);
				retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text1);

			}
		} else if (StringUtils.isNotBlank(currentQues.getNmlineoperate())) {
			//跳转 下一题
			nextQuestion = RobotTools.getQuestion(currentQues.getOrgi(), currentQues.getNmlineoperate()) ;

			isAddNext = true;
			if(nextQuestion!=null) {
				retMessage = nextQue(process , robotParam, dataBean , statusEvent , aiUser, nextQuestion, voiceResultList);
			}
			if(queSurveyResultAnswer!=null) {
				queSurveyResultAnswer.setAnstatus("next");
			}
		}
		return isAddNext ;
	}
	/**
	 * 智能机器人asr结果处理
	 * @param robotParam
	 * @param callid
	 * @param extention
	 * @param callerid
	 * @param dataBean
	 * @return
	 * @throws JSONException
	 */
	@SuppressWarnings("unused")
	public RobotReturnParam aiasrProcess(RobotParam robotParam, String callid, Extention extention, String callerid,
									   UKDataBean dataBean , AiUser aiUser) throws JSONException {
		RobotReturnParam robotReturnParam = null;
		if (aiUser != null && aiUser.isBussend() == false) {
			ChatMessage data = newChatMsg(aiUser,null);
			//TODO 返回 客户说话时长
			/*AsrResult asrResult = UKTools.parseAsrResult(robotParam.getCdrid(), robotParam.getText(),
					0);*/
			AsrResult asrResult = new AsrResult(robotParam.getCdrid(), robotParam.getText(),"0");

			if(StringUtils.isNotBlank(robotParam.getWavfile())){
				asrResult.setRecordpath(robotParam.getWavfile());
			}
			data.setAiid(extention.getAiid());
			if (asrResult != null && !StringUtils.isBlank(asrResult.getMessage())) {
				asrResult.setMessage(asrResult.getMessage().replaceAll("[\\p{P}+~$`^=|<>～｀＄＾＋＝｜＜＞￥×]", ""));
				if (asrResult.getMessage().endsWith("。")) {
					data.setMessage(asrResult.getMessage().substring(0, asrResult.getMessage().length() - 1));
				} else {
					data.setMessage(asrResult.getMessage());
				}
				data.setDuration((int) Math.ceil(asrResult.getSpeakms() / 1000f));
				data.setExpmsg(asrResult.getMessage());
				List<VoiceResult> voiceResultList = new ArrayList<VoiceResult>();

				//TODO 确认录音地址
				if (!StringUtil.isBlank(data.getMessage())) {
					if(!StringUtils.isBlank(asrResult.getRecordpath())) {
						if(asrResult.getRecordpath().indexOf("|") > 0) {
							data.setUrl(asrResult.getRecordpath().substring(0,asrResult.getRecordpath().indexOf("|")));
						}else {
							data.setUrl(asrResult.getRecordpath());
						}
					}
				}
				data.setMediaid(robotParam.getCdrid());

				/**
				 * 输入消息
				 */
				MessageUtils.createAiMessage(data, data.getAppid(), UKDataContext.ChannelTypeEnum.PHONE.toString(),
						UKDataContext.CallTypeEnum.IN.toString(), UKDataContext.AiItemType.USERINPUT.toString(),
						UKDataContext.MediaTypeEnum.TEXT.toString(), data.getUserid());
				/**
				 * 使用 ASR识别结果作为消息内容
				 */
				data.setMessage(data.getExpmsg());

				ChatMessage retMessage = null;
				if (!StringUtils.isBlank(aiUser.getAitype())
						&& aiUser.getAitype().equals(UKDataContext.AiType.BUSINESSAI.toString())) {


				} else {
					//智能机器人 分开接口
					data.setMediaid("");
					retMessage = aiMessageProcesser.chat(data);
					aiUser.setRetimes(0);
				}
				/**
				 * 回复消息
				 */
				if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
					retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
							retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
							UKDataContext.AiItemType.AIREPLY.toString(),
							UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

					//智能机器人
					String retText = retMessage != null && !StringUtils.isBlank(retMessage.getMessage())
							? retMessage.getMessage()
							: extention.getTipmessage();
					if (!StringUtils.isBlank(retText)) {
						List<String> voices = new ArrayList<>();
						if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(retMessage.getMsgtype())) {
							String tts = null;
							if (!StringUtils.isBlank(retMessage.getMessage())) {
								tts = Jsoup.parse(retMessage.getMessage()).text();
								if (tts.length() > 300) {
									tts = tts.substring(0, 300);
								}
								voices.add(processMessage(tts, dataBean, aiUser));
							}
						} else {
							voices.add(retMessage.getMessage());
						}
						//外部机器人挂断
						if (UKDataContext.MediaTypeEnum.HUNGUP.toString().equalsIgnoreCase(retMessage.getBustype())) {
							robotReturnParam = hangUpList(voices, aiUser);
						} else if (UKDataContext.MediaTypeEnum.TRANS.toString().equalsIgnoreCase(retMessage.getBustype())) {
							//转接
							aiUser.setTrans(retMessage.getCode());
							robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
						} else {
							robotReturnParam = defaultplayback(voices, aiUser);
						}
					}
					CacheHelper.getAiUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
				}
			}
		} else {
			//map = hangUp();
		}
		if (robotReturnParam == null) {
			robotReturnParam = noop(true,aiUser);
		}
		return robotReturnParam;
	}

	/**
	 * 判断结果是否命中关键词
	 *
	 * @param configKeyWord
	 * @param keyword
	 * @return
	 */
	private boolean matchKeyWord(String configKeyWord, String keyword, boolean include) {
		boolean match = false;
		if (!StringUtils.isBlank(keyword)) {
			keyword = keyword.trim();
			if (!StringUtils.isBlank(configKeyWord)) {
				String[] keywords = configKeyWord.split("[,，]");
				for (String kw : keywords) {
					//kw = kw.replaceAll("\\*", "[\\\\S\\\\s]*?");
					kw = kw.trim();
					if (!StringUtils.isBlank(kw)) {
						try {
							if (keyword.matches(kw)) {
								match = true;
								break;
							}
						}catch(Exception ex) {
							ex.printStackTrace();
						}
						if (include && keyword.equals(kw)) {
							match = true;
							break;
						}
					}
				}
			}
		}
		return match;
	}


	/**
	 * 放音
	 * @param message
	 * @param aiuser
	 * @return
	 */
	public RobotReturnParam fangyinList(List<String> message, AiUser aiuser) {

		RobotReturnParam robotReturnParam = new RobotReturnParam(aiuser);

		List<String> playbackMusic = new ArrayList<String>();
		if (message.size() > 0) {
			for (String s : message) {
				//TODO ？
				if (StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}
		robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
		//如果没录音 没匹配到 "param2":"1",    扩展参数2,="-9"表示识别出来的文本没匹配到关键字,暂停的语音继续播放
		if (playbackMusic.size() == 0) {
			robotReturnParam = noop(true,aiuser);
		}

		return robotReturnParam;
	}

	/**
	 * 根据流程，组装对应的放音json
	 *
	 * @param flow 放音音频
	 * @author cxy
	 * @version 2018-04-15
	 */
	/*public RobotReturnParam playback(List<String> music, AiUser aiUser) {
		RobotReturnParam robotReturnParam = new RobotReturnParam();

		if (aiUser.isInterrupt()) {
			flowdata.put("interrupt", "1");
		}

		*//*Map<String, Object> map = new HashMap<String, Object>();
		map.put("action", "playback");
		// 缓存中取出这步的业务名称
		Map<String, String> flowdata = processFlowData("default");
		if (aiUser.isInterrupt()) {
			flowdata.put("interrupt", "1");
		}
		map.put("flowdata", flowdata);
		Map<String, Object> params = new HashMap<String, Object>();*//*
		List<String> playbackMusic = new ArrayList<String>();
		if (music.size() > 0) {
			for (String s : music) {
				if (StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}
		params.put("max_speak_ms", aiUser.getMaxspreak());

		params.put("prompt", playbackMusic);
		params.put("wait", aiUser!=null && aiUser.getLastreplytime() > 0 ?aiUser.getLastreplytime() : waittime);
		params.put("retry", 0);
		params.put("allow_interrupt", aiUser.isInterrupt() ? aiUser.getInterrupttime() : -1);//0允许，-1不允许，大于0 播放多久才允许自动打断
		params.put("block_asr", aiUser.isInterrupt() ? aiUser.getInterrupttime() : -1);

		//设置了语种/方言  就读取对应的配置文件路径
		if (aiUser != null && StringUtils.isNotBlank(aiUser.getLanguage()) && StringUtils.isNotBlank(aiUser.getLanguagepath())) {
			params.put("tts_configure_filename", aiUser.getLanguagepath());
		}

		map.put("params", params);
		if (playbackMusic.size() == 0) {
			map = noop(null);
		}
		return map;
	}*/

	/**
	 * 流程中放音
	 * @param music
	 * @param aiUser
	 * @return
	 */
	public RobotReturnParam defaultplayback(List<String> music, AiUser aiUser) {
		RobotReturnParam robotReturnParam = new RobotReturnParam(aiUser);

		List<String> playbackMusic = new ArrayList<String>();

		if (music.size() > 0) {
			for (String s : music) {
				if (!StringUtils.isBlank(s) && StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}
		//超时时间
		robotReturnParam.setAsrtimeout(aiUser!=null && aiUser.getLastreplytime() > 0 ?aiUser.getLastreplytime()/1000+"" : waittime/1000 + "");

		//是否允许打断 允许打断开始时长
		if(aiUser.isInterrupt() && aiUser.getInterrupttime() > 0){
			robotReturnParam.setAsrtimeout(robotReturnParam.getAsrtimeout() + "|" + aiUser.getInterrupttime()/1000);
		}
		if(aiUser.isInterrupt()){
			robotReturnParam.setAsrvoice(StringUtils.join(playbackMusic,";"));
		}else{
			robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
			robotReturnParam.setAsrvoice("m00.wav");
		}

		//如果没录音 没匹配到 "param2":"1",    扩展参数2,="-9"表示识别出来的文本没匹配到关键字,暂停的语音继续播放
		if (playbackMusic.size() == 0) {
			robotReturnParam = noop(true,aiUser);
		}


		return robotReturnParam;
	}

	/**
	 * 放音后挂断
	 * @return
	 */
	public RobotReturnParam hangUp() {
		RobotReturnParam robotReturnParam = new RobotReturnParam();
		// <0 为挂机
		robotReturnParam.setQueueid("-1");
		return robotReturnParam;
	}

	/**
	 * 未匹配中结果 ， 继续播放录音
	 * @return
	 */
	/*public RobotReturnParam consolePlayback() {
		RobotReturnParam robotReturnParam = new RobotReturnParam();
		robotReturnParam.setParam2("-9");

		return robotReturnParam;
	}*/

	/**
	 * 挂断
	 * @param voice
	 * @param aiuser
	 * @return
	 */
	public RobotReturnParam hangUpList(List<String> voice, AiUser aiuser) {

		RobotReturnParam robotReturnParam = new RobotReturnParam(aiuser);
		// <0 为挂机
		robotReturnParam.setQueueid("-1");

		List<String> playbackMusic = new ArrayList<>();
		if (voice.size() > 0) {
			for (String s : voice) {
				if (StringUtils.isNotBlank(s)) {
					playbackMusic.add(s);
				}
			}
		}else{
			playbackMusic.add("m00.wav");
		}
		//延迟挂机
		if(aiuser.getDelaytime() > 0){
			robotReturnParam.setAsrtimeout((aiuser.getDelaytime()/1000) + "");
		}else {
			robotReturnParam.setAsrtimeout("0");
		}

		robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
		return robotReturnParam;

	}


	/**
	 * 转接 transfer 形式
	 *
	 * @param number
	 * @param voice
	 * @return
	 */
	public RobotReturnParam transfer(String number, List<String> voice, AiUser aiuser) {

		RobotReturnParam robotReturnParam = new RobotReturnParam(aiuser);

		// >0 转接号码
		robotReturnParam.setQueueid(number);
		List<String> playbackMusic = new ArrayList<>();
		if (voice.size() > 0) {

			for (String s : voice) {
				if (!StringUtils.isBlank(s) && StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}else{
			playbackMusic.add("m00.wav");
		}
		robotReturnParam.setAsrtimeout("0");
		
		robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
		return robotReturnParam;

	}

	/**
	 * 挂断后操作
	 *
	 * @param aiUser
	 * @param extention
	 */
	private void afterleave(AiUser aiUser, Extention extention, UKDataBean dataBean,RobotParam robotParam) {
		QueSurveyResult queSurveyResult = aiUser.getResult();

		AiCallOutProcess process = null;
		// 话术or问卷
		if (extention.getBustype().equals("sale")) {
			process = RobotTools.getAiProcess(extention.getProid(), extention.getOrgi());
		} else {
			process = RobotTools.getProcess(extention.getQueid(), extention.getOrgi()) ;
		}
		int sumscore = 0;
		// 问卷结果主表
		if (queSurveyResult != null) {
			int focustimes = 0;//关注点次数
			String level = "";
			if(process.isResult()) {
				LinkedList<QueSurveyResultQuestion> list = aiUser.getQuestionList();
				if (list.size() > 0) {
					for (Iterator<QueSurveyResultQuestion> iter = list.iterator(); iter.hasNext(); ) {
						List<QueSurveyResultPoint> resultPointList = new ArrayList<>();
						QueSurveyResultQuestion q = iter.next();
						if (q.getEndtime() != null && q.getCreatetime() != null) {
							q.setProcesstime(new Long(q.getEndtime().getTime() - q.getCreatetime().getTime()).intValue());
						}
						q.setStatuseventid(robotParam.getCdrid());
						int qsumscore = 0;
						int focustimesq = 0;
						if ("1".equals(process.getScore())) {
							//统计每个问题初始分
							sumscore = sumscore + q.getScore();
							List<SalesPatterPoint> pointList = RobotTools.getSalesPatterPoint(q.getQuestionid(), aiUser.getOrgi());
							if (pointList != null && pointList.size() > 0) {
								for (SalesPatterPoint point : pointList) {
									if ("0".equals(point.getPointtype()) && q.getAnswer()!=null) {
										//关键字匹配
										String[] answers = q.getAnswer().split("[,\\\\|，]");
										for (String answerword : answers) {
											boolean match = matchKeyWord(point.getFocusword(), answerword, false);
											if (match) {
												qsumscore = qsumscore + point.getScore();
												focustimes++;
												focustimesq++;
												//记录匹配关注点
												QueSurveyResultPoint qpoint = new QueSurveyResultPoint();
												qpoint.setEventid(queSurveyResult.getEventid());
												qpoint.setResultid(queSurveyResult.getId());
												qpoint.setProcessid(q.getProcessid());
												qpoint.setPointid(point.getId());
												qpoint.setQuestionid(q.getQuestionid());
												qpoint.setOrgi(q.getOrgi());
												qpoint.setCreater(q.getCreater());
												qpoint.setCreatetime(new Date());
												qpoint.setPointtype(point.getPointtype());
												qpoint.setFocusword(point.getFocusword());
												qpoint.setMaxcalltime(point.getMaxcalltime());
												qpoint.setMincalltime(point.getMincalltime());
												qpoint.setScore(point.getScore());
												qpoint.setAnswer(answerword);
												qpoint.setPointname(point.getName());
												qpoint.setStatuseventid(q.getStatuseventid());
												resultPointList.add(qpoint);
											}
										}
									} else {
										//判断通话时长
										if (point.getMincalltime() != null && point.getMaxcalltime() != null) {
											if (q.getProcesstime() >= point.getMincalltime() * 1000 && q.getProcesstime() <= point.getMaxcalltime() * 1000) {
												qsumscore = qsumscore + point.getScore();
												focustimes++;
												focustimesq++;
												//记录匹配关注点
												QueSurveyResultPoint qpoint = new QueSurveyResultPoint();
												qpoint.setEventid(queSurveyResult.getEventid());
												qpoint.setResultid(queSurveyResult.getId());
												qpoint.setProcessid(q.getProcessid());
												qpoint.setPointid(point.getId());
												qpoint.setQuestionid(q.getQuestionid());
												qpoint.setOrgi(q.getOrgi());
												qpoint.setCreater(q.getCreater());
												qpoint.setCreatetime(new Date());
												qpoint.setPointtype(point.getPointtype());
												qpoint.setFocusword(point.getFocusword());
												qpoint.setMaxcalltime(point.getMaxcalltime());
												qpoint.setMincalltime(point.getMincalltime());
												qpoint.setScore(point.getScore());
												qpoint.setAnswertime(q.getProcesstime());
												qpoint.setPointname(point.getName());
												qpoint.setStatuseventid(q.getStatuseventid());
												resultPointList.add(qpoint);
											}
										}
									}
								}
							}
							//统计每个问题关注点得分
							sumscore = sumscore + qsumscore;
							q.setSumscore(qsumscore);
							q.setFocustimes(focustimesq);
						}
						q.setProcessid(aiUser.getQueresultid());
						q.setNameid(queSurveyResult.getNameid());
						q.setResultid(queSurveyResult.getId());
						questionResultRes.save(q);
						if (resultPointList.size() > 0) {
							for (QueSurveyResultPoint r : resultPointList) {
								r.setResultqueid(q.getId());
								r.setNameid(q.getNameid());
								resultPointRes.save(r);
							}
						}
					}
				}
			
				if ("1".equals(process.getScore())) {
					List<QueSurveyResultAnswer> queSurveyResultAnswerList = UKDataContext.getContext().getBean(QueSurveyResultAnswerRepository.class).findByResultidAndProcessidAndOrgi(queSurveyResult.getId(), process.getId(),
							aiUser.getOrgi());
					//统计每个问题 答案分数
					if (queSurveyResultAnswerList.size() > 0) {
						for (QueSurveyResultAnswer a : queSurveyResultAnswerList) {
							sumscore = sumscore + a.getAnswerscore();
						}
					}
				}
				//计算评级
				if ("1".equals(process.getScore())) {
					List<SalesPatterLevel> levelList = RobotTools.getSalesPatterLevel(process.getId(), aiUser.getOrgi());
					for (SalesPatterLevel sptl : levelList) {
						if (sptl.getMinscore() != null && sptl.getMaxscore() != null) {
							if (sumscore >= sptl.getMinscore() && sumscore <= sptl.getMaxscore()) {
								level = sptl.getName();
							}
						}
					}
				}
				if (dataBean != null) {
					dataBean = SearchTools.get(StringUtils.isNotBlank(dataBean.getType()) ? dataBean.getType() : (dataBean.getTable() != null ? dataBean.getTable().getTablename() : ""), (String) dataBean.getValues().get("id"));
					if (dataBean != null) {
						//只更新以下字段
						UKDataBean updateBean = new UKDataBean();
						updateBean.setType(dataBean.getType());
						updateBean.setId(dataBean.getId());
						Map<String, Object> map = new HashMap<>();
						map.put("id", StringUtils.isNotBlank(dataBean.getId()) ? dataBean.getId() : dataBean.getValues().get("id"));
						map.put("levelscore", sumscore);
						map.put("focustimes", focustimes);
						map.put("level", level);
						updateBean.setValues(map);
						SearchTools.updateAndRefresh(updateBean, true);
	
					}
				}
				queSurveyResult.setSumscore(Integer.toString(sumscore));
				queSurveyResult.setTimeouttimes(aiUser.getTimeoutnums());
				queSurveyResult.setErrortimes(aiUser.getErrortimes());
				queSurveyResult.setRetimes(aiUser.getRetimes());
				queSurveyResult.setEndtime(new Date());
				queSurveyResult.setStatuseventid(robotParam.getCdrid());
				queSurveyResult.setProcesstime(
						new Long(new Date().getTime() - queSurveyResult.getCreatetime().getTime())
								.intValue());
				queSurveyResult.setFocustimes(focustimes);
				queSurveyResult.setLevel(level);
				queSurveyResultRes.save(queSurveyResult);
			}

			StatusEvent statusEvent = RobotTools.getStatusEvent(robotParam.getCdrid(), extention.getOrgi());

			if(statusEvent != null){
				
				CallOutNames callOutNames = null ;
				if(statusEvent!=null && !StringUtils.isBlank(statusEvent.getNameid()) && !StringUtils.isBlank(statusEvent.getOrgi())) {
					callOutNames = (CallOutNames) CacheHelper.getCallOutCacheBean().getCacheObject(statusEvent.getNameid(), statusEvent.getOrgi());
					if(callOutNames == null) {
						callOutNames = callOutNamesRes.findByIdAndOrgi(statusEvent.getNameid(), statusEvent.getOrgi()) ;
					}
				}
				StatusEventRobot statusEventRobot = new StatusEventRobot();
				statusEventRobot.setId(statusEvent.getId());
				statusEventRobot.setLevel(level);
				statusEventRobot.setLevelscore(sumscore);
				statusEventRobot.setFocustimes(focustimes);
				statusEventRobot.setProcessid(process.getId());
				if(!StringUtils.isBlank(statusEvent.getNameid())) {
					if(callOutNames!=null) {
						statusEventRobot.setAitransqus(callOutNames.getAitransqus());
						statusEventRobot.setAitranstime(callOutNames.getAitranstime());
						statusEventRobot.setAitransduration(callOutNames.getAitransduration());
					}
				}
				statusEventRobot.setAitrans(aiUser.isAgent());

				statusEventRobot.setErrortimes(aiUser.getErrortimes());
				statusEventRobot.setTimeouttimes(aiUser.getTimeoutnums());
				statusEventRobot.setNmlinetimes(aiUser.getNmline());
				
				statusEventRobot.setAieventid(statusEvent.getId());
				
				statusEventRobot.setAsrtimes(aiUser.getAsrtimes());
				statusEventRobot.setTtstimes(aiUser.getTtstimes());
				statusEventRobot.setAi(true);
				
				statusEventRobotRes.save(statusEventRobot);
			}
		}
	}

	/**
	 * 跳转下一题
	 * @param aiUser
	 * @param nextQuestion
	 * @param voiceResultList
	 */
	private ChatMessage nextQue(AiCallOutProcess process , RobotParam robotParam ,UKDataBean dataBean ,StatusEvent statusEvent,AiUser aiUser,QueSurveyQuestion nextQuestion,List<VoiceResult> voiceResultList){
		//下个问题
		aiUser.setDataid(nextQuestion.getId());
		aiUser.setAiqustitle(nextQuestion.getTitle());
		//设置是否允许打断 最大说话时长
		aiUser.setInterrupt(nextQuestion.isInterrupt());
		aiUser.setInterrupttime(nextQuestion.getInterrupttime() * 1000);
		aiUser.setMaxspreak(nextQuestion.getMaxspreak() * 1000);
		//设置 等待超时时长
		aiUser.setLastreplytime(nextQuestion.getOvertime() * 1000);
		aiUser.setBridge(false);

		aiUser.setErrortimes(0);
		aiUser.setRetimes(0);
		aiUser.setTimeoutnums(0);
		ChatMessage retMessage = newChatMsg(aiUser,nextQuestion);
		
		/**
		 * 是否需要发送短信
		 */
		if(nextQuestion.isEnablesms() && !StringUtils.isBlank(nextQuestion.getSmsid())) {
			procesSMS(process,  robotParam ,dataBean, statusEvent, aiUser, nextQuestion);
		}
		
		if (!StringUtils.isBlank(nextQuestion.getWvtype())
				&& nextQuestion.getWvtype().equals("voice")) {
			retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
			retMessage.setMessage(nextQuestion.getQuevoice());

			retMessage.setMessage((StringUtils.isNotBlank(nextQuestion.getName()) ? nextQuestion.getName() : nextQuestion.getQuevoice()));
			retMessage.setExpmsg(nextQuestion.getQuevoice());

			voiceResultList
					.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
							null, nextQuestion.getQuevoice()));
		} else {
			retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
			retMessage.setMessage(nextQuestion.getName());
			retMessage.setExpmsg(nextQuestion.getName());
			voiceResultList
					.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
							nextQuestion.getName(), null));
		}
		if(nextQuestion.isNmline()) {
			if(nextQuestion.getNmlinetype() > 0) {
				aiUser.getNmlinetype()[nextQuestion.getNmlinetype()] = (byte) (aiUser.getNmlinetype()[nextQuestion.getNmlinetype()]+1);
			}
			aiUser.setNmline(aiUser.getNmline()+1);
		}
		if(nextQuestion.isQusbussop() && !StringUtils.isBlank(nextQuestion.getQusbusslist())) {
			String[] busslist = nextQuestion.getQusbusslist().split(",") ;
			for(String buss : busslist) {
				switch(buss) {
				case "contacts" : 
					OnlineUserUtils.processContacts(aiUser, dataBean,nextQuestion.getOrgi() , false,nextQuestion.getQusbusslist().indexOf("quality") >= 0);
					break ;
				case "event" : 
					OnlineUserUtils.processEvent(entityManager, aiUser, dataBean, nextQuestion.getOrgi(), statusEvent,nextQuestion.getQusbusslist().indexOf("quality") >= 0);
					aiUser.setEvent(true);
					
					/**
					 * 保存联系人动作
					 */
					if(aiUser.getContacts() != null) {
						contactsRes.save(aiUser.getContacts()) ;
						
						if(aiUser.getContacts()!=null && dataBean != null && dataBean.getValues()!=null) {
							dataBean.getValues().put("conid",aiUser.getContacts().getId()) ;
							SearchTools.save(dataBean);
						}
					}
					default : 
						break;
				}
			}
		}
		/**
		 * 非主线
		 */
		if(!StringUtils.isBlank(nextQuestion.getNmlinerepeat())
				&& nextQuestion.getNmlinerepeat().matches("[1-9]") && 
				(
						!StringUtil.isBlank(nextQuestion.getNmlinetypematch()) && nextQuestion.getNmlinetypematch().matches("[1-9]") ? 
						aiUser.getNmlinetype()[Integer.parseInt(nextQuestion.getNmlinetypematch())] >= Integer.parseInt(nextQuestion.getNmlinerepeat()) :
						aiUser.getNmline() >= Integer.parseInt(nextQuestion.getNmlinerepeat()) 
				)
		) {
			/**
			 * 
			 * 清空Voice，不再播放
			 */
			voiceResultList.clear();
			/**
			 * 错误中断，非主线节点
			 */
			processNmline(process ,robotParam,  dataBean ,aiUser, nextQuestion, null, voiceResultList, "", retMessage, nextQuestion, statusEvent) ;
		}else {
			if (2 == nextQuestion.getQuetype()) {
				// 一个问题为结束节点 结束通话hangup
				aiUser.setBussend(true);
			} else if (3 == nextQuestion.getQuetype()) {
				aiUser.setBridge(true);
				aiUser.setTrans(nextQuestion.getTrans());
			} else if (4 == nextQuestion.getQuetype()) {
				//
				String trans = transAgent(statusEvent , aiUser, nextQuestion.getId(),nextQuestion, retMessage, voiceResultList);
				if(!StringUtils.isBlank(trans)) {
					aiUser.setBridge(true);
					aiUser.setTrans(trans);
				}
			} else if (5 == nextQuestion.getQuetype() && !StringUtils.isBlank(nextQuestion.getTransnode())) {//转话术节点
				//跳转 下一题
				nextQuestion = RobotTools.getQuestion(nextQuestion.getOrgi(),nextQuestion.getTransnode()) ;
				
				/**
				 * 记录 , 跳转到下一题，记录当前节点的 对话记录
				 */
				MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
						retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
						UKDataContext.AiItemType.AIREPLY.toString(),
						UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());
				
				retMessage = nextQue(process , robotParam, dataBean , statusEvent , aiUser,nextQuestion,voiceResultList);
			}
		}
		
		if(process!=null && process instanceof SalesPatter && aiUser.isBussend() == false && aiUser.isBridge() == false) {
			SalesPatter patter = (SalesPatter)process ;
			if(patter.isEnabletransfercon()) {
				SysDic dic = null ;
				boolean exec = false ;
				int time = 0 ;
				if(aiUser.getTime() > 0) {
					time = (int) ((System.currentTimeMillis() - aiUser.getTime()) / 1000);
				}
				if(!StringUtils.isBlank(patter.getTransferconditions()) && (dic = UKeFuDic.getInstance().getDicItem(patter.getTransferconditions()))!=null) {
					if (dic.getCode().equals("time") && (!StringUtils.isBlank(patter.getTransfervalue())
							&& patter.getTransfervalue().matches("[\\d]{1,3}")
							&& time >= Integer.parseInt(patter.getTransfervalue()))) {
						exec = true ;
					}else if (dic.getCode().equals("agents") && CallOutQuene.updateAgentStatus(patter.getTransferactivity() , patter.getOrgi()) != null) {
						exec = true ;
					}
				}
				if(exec == true) {
					if (2 == patter.getQuetype()) {
						// 一个问题为结束节点 结束通话hangup
						aiUser.setBussend(true);
					} else if (3 == patter.getQuetype()) {
						aiUser.setBridge(true);
						aiUser.setTrans(patter.getTrans());
					} else if (4 == patter.getQuetype()) {
						//
						String trans = transAgent(statusEvent , aiUser,nextQuestion.getId() , patter , retMessage, voiceResultList);
						if(!StringUtils.isBlank(trans)) {
							aiUser.setBridge(true);
							aiUser.setTrans(trans);
						}
					}
				}
			}
		}
		
		return retMessage;
	}
	/**
	 * 
	 * @param process
	 * @param dataBean
	 * @param statusEvent
	 * @param aiUser
	 * @param question
	 */
	private void procesSMS(AiCallOutProcess process , RobotParam param, UKDataBean dataBean ,StatusEvent statusEvent,AiUser aiUser,QueSurveyQuestion question) {
		if(question.isEnablesms() && !StringUtils.isBlank(question.getSmsid())) {
			if(param!=null && !StringUtils.isBlank(param.getTelno())) {
				UKTools.published(new CommandSms(param.getTelno() , question.getSmsid() , dataBean , UKDataContext.UKEFU_SYSTEM_SALESPATTER.toString() , aiUser.getOrgi()));
			}
		}
	}

	private ChatMessage newChatMsg(AiUser aiUser,QueSurveyQuestion nextQuestion){
		ChatMessage retMessage = new ChatMessage();
		retMessage.setMessage(nextQuestion != null ? nextQuestion.getName():"");
		retMessage.setAppid(aiUser.getAppid());
		retMessage.setUserid(aiUser.getUserid());
		retMessage.setUsername("小E");
		retMessage.setAichat(true);
		retMessage.setChannel(aiUser.getChannel());
		retMessage.setType(UKDataContext.MessageTypeEnum.MESSAGE.toString());
		retMessage.setContextid(aiUser.getContextid());
		retMessage.setOrgi(aiUser.getOrgi());
		retMessage.setAgentserviceid(aiUser.getAgentserviceid());
		return retMessage;
	}

	/**
	 * 
	 * @param statusEvent
	 * @param aiUser
	 * @return
	 */
	private CallHangup createHangupInfo(StatusEvent statusEvent , AiUser aiUser) {
		CallHangup callHangup = new CallHangup();
		
		callHangup.setId(statusEvent.getId());
		callHangup.setAgent(statusEvent.getAgent());
		callHangup.setAsrtimes(String.valueOf(aiUser.getAsrtimes()));
		callHangup.setCallid(statusEvent.getId());
		callHangup.setCity(aiUser.getIpdata().getCity());
		callHangup.setProvince(aiUser.getIpdata().getProvince());
		callHangup.setIsp(aiUser.getIpdata().getIsp());
		callHangup.setCalled(statusEvent.getDisphonenum());
		
		callHangup.setCreater(statusEvent.getCreater());
		callHangup.setCreatetime(new Date());
		if(statusEvent.getStarttime()!=null) {
			callHangup.setDuration((int)(System.currentTimeMillis() - statusEvent.getStarttime().getTime())/1000);
		}
		callHangup.setGateway(statusEvent.getGateway());
		callHangup.setHangupansid(aiUser.getAitransans());
		callHangup.setHangupqusid(aiUser.getDataid());
		callHangup.setOrgi(statusEvent.getOrgi());
		callHangup.setQusid(aiUser.getDataid());
		callHangup.setAnsid(aiUser.getAitransans());
		callHangup.setRingduration(statusEvent.getRingduration());
		
		callHangup.setAnsid(aiUser.getAitransans());
		callHangup.setAnstitle(aiUser.getAianstitle());
		
		callHangup.setQusid(aiUser.getDataid());
		callHangup.setQustitle(aiUser.getAiqustitle());
		
		callHangup.setHangupansid(aiUser.getAitransans());
		callHangup.setHangupanstitle(aiUser.getAianstitle());
		
		callHangup.setHangupqusid(aiUser.getDataid());
		callHangup.setHangupqustitle(aiUser.getAiqustitle());
		
		if(aiUser.isPubans()) {
			callHangup.setQustitle(aiUser.getAianstitle());
			callHangup.setAnstitle("default");
		}
		
		/**
		 * 挂断发起方 ， 如果系统挂机，需要记录全部的挂断原因，挂断问题和答案，如果是用户挂机，只记录一个 default
		 */
		if(aiUser.isBussend()) {
			callHangup.setHangupinitiator("agent");
		}else {
			callHangup.setHangupinitiator("user");
			callHangup.setAnstitle("default");
			
		}
		
		return callHangup ;
	}
}
